Search code examples
powershellselect-string

Powershell parse unformatted text file


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!


Solution

  • 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.