0

I am trying to parse a text file which is basically in a following format:

Name: James

Location: UK

I think it makes most sense to use Select-String:

$getName = "C:\account.txt"
Select-String -Path  $getName -Pattern 'Name:   '

However, this will return way more than I need. Can somebody please advise me how to get "James" and "UK" as different strings.

Thank you!

cel09
  • 63
  • 3
  • 8
  • Are you having Name and location on same line or on different lines ? – Venkataraman R Sep 15 '20 at 08:11
  • Different lines – cel09 Sep 15 '20 at 08:19
  • Did you consider using `"Get-Content" | Where-Object...` ? You want the content not the path or? Cause if you want to know in which file the string "James" is, then you would use `Select-String` – Adis1102 Sep 15 '20 at 08:39
  • You are correct! It makes way more sense. I will try something, should you have any examples regarding my case it would be super helpful. Thanks – cel09 Sep 15 '20 at 08:43

1 Answers1

4

Do you mean this...

# Create user data sample and use regex match to get name and location only
Clear-Host
@'
Name: James
SomeOtherData: 
Location: UK
MoreStuff: 
'@ | Out-File -LiteralPath 'D:\Temp\account.txt'


Get-Content -Path 'D:\Temp\account.txt' | 
ForEach-Object {$PSItem | Select-String -Pattern '^(Name:\s|Location:\s).*'}
# Results
<#
Name: James
Location: UK
#>

Or this...

Get-Content -Path 'D:\Temp\account.txt' | 
ForEach-Object {($PSItem | Select-String -Pattern '^(Name:\s|Location:\s).*') -replace '.*:\s'}
# Results
<#
James
UK
#>

There are a number of ways to do this. Meaning, list format as shown or table format.

Also, take a look at the ConvertFrom-String cmdlet, to convert the strings to an object.

Clear-Host
$template = @'
{Property*:Name:} {Value:James}
{Property*:Location:} {Value:UK}
'@

$testText = @'
Name: James
SomeOtherData: 
Location: UK
MoreStuff: 
'@

I am using PowerShell variable squeezing to assign to the variable and output to the screen at the same time. 'This is not required.' It's just a shortcut to do two things at once when needed.

(
$PersonalData = $testText | 
ConvertFrom-String -TemplateContent $template
)
# Results
<#
Property  Value
--------  -----
Name:     James
Location: UK  
#>

$PersonalData.Property
# Results
<#
Name:
Location:
#>


$PersonalData.Value
# Results
<#
James
UK
#>

(
$PersonalData = Get-Content -Path 'D:\Temp\account.txt'  | 
ConvertFrom-String -TemplateContent $template
)
# Results
<#
Property  Value
--------  -----
Name:     James
Location: UK  
#>

All the aforementioned are well documented, the PowerShell help files, MS Docs site, in blogs...

'PowerShell parsing text file' ...and videos on Youtube.

postanote
  • 15,138
  • 2
  • 14
  • 25