Varun
Varun

Reputation: 5

How to find Domain & Username from a line in text file using Powershell

I need to extract domain\username from text file.

Sample Line to extract domain\username only:

<![LOG[The logged on user is LEO\userpc]LOG]!><time="02:42:14.378+420" date="09-09-2021" component="execmgr" context="" type="1" thread="6460" file="execreqmgr.cpp:5003">

Code i tried:

$filter  = Get-Content C:\Windows\ccm\logs\execmgr.log  | Where-Object { $_.Contains("LEO") } | select -Last 1 

$fil = $filter.Replace('<![LOG[The logged on user is ','')

Get-Content $fil | ForEach-Object {
  if ( $_ -match '^LEO' ) {
    $_ -replace '-', 'x'
  }
  else {
    $_
  }
} 

Upvotes: 0

Views: 356

Answers (1)

Theo
Theo

Reputation: 61068

For strings like that, I would use a regex like this:

([regex]'The logged on user is\s+([^\]]+)').Match((Get-Content -Path 'C:\Windows\ccm\logs\execmgr.log' -Raw)).Groups[1].Value

Upvotes: 1

Related Questions