Search code examples
c#powershellpowershell-3.0

How to select a string which starts with and ends with a pattern in powershell?


I have a text file which contains the following data, and I am trying to grab the string which starts with "WaitInstance" and end with a single quote.

Some Data
Run 'WaitInstance -Id 000EACF-AAA-BBBB-9999-D864A60EDDF3' command to tell when it is available
Some Data

So I want the following data from the above file in a variable

WaitInstance -Id 000EACF-AAA-BBBB-9999-D864A60EDDF3

I am using the following code to match the pattern, but powershell is extracting the entire line from the file:

$SEL = Select-String -Path 'C:\Users\File.txt' -Pattern "WaitInstance"

Solution

  • Regular expressions to the rescue:

    $r = [RegEx]"(WaitInstance.*)'"
    
    Get-Content "C:\Users\File.txt" `
     | ForEach-Object { $r.Match($_) } `
     | Where-Object { $_.Success } `
     | ForEach-Object { $_.Groups[1].Value }
    
    

    To understand the final code block you can just do one line at a time:

    Pipe out each line of the file:

    Get-Content "C:\Users\File.txt"
    

    Pipe out each line of the file, and convert it to a regular expression match result:

    Get-Content "C:\Users\File.txt" `
     | ForEach-Object { $r.Match($_) }
    

    Pipe out each line of the file, and convert each to a regular expression match result, and filter out the ones that didn't match the pattern

    Get-Content "C:\Users\File.txt" `
     | ForEach-Object { $r.Match($_) } `
     | Where-Object { $_.Success }
    

    Pipe out each line of the file, and convert each to a regular expression match result, and filter out the ones that didn't match the pattern, and then extract the part you are interested in (which is the part in brackets in the regular expression):

    Get-Content "C:\Users\File.txt" `
     | ForEach-Object { $r.Match($_) } `
     | Where-Object { $_.Success } `
     | ForEach-Object { $_.Groups[1].Value }