Search code examples
arrayspowershellvariablesforeachselect-string

Taking the last word of each line from Select-String


I'm stuck on a problem pulling text from a file. Here's what I ultimately want to do:

  1. Search through a specific file for instances of the phrase "NoRequest".
  2. ONLY take the value of NoRequest. i.e. if NoRequest = true, then it would only add "true" to the array, not the whole line.
  3. Do this for each instance of the phrase in the file.

Here's a snippet of the section I'm working on:

$FileContents = Select-String -Path "C:\Users\me\Documents\file.ini" -Pattern "NoRequest"

When I use that line, I get the following:

PS> $FileContents
Documents\file.ini:222:NoRequest = false
Documents\file.ini:281:NoRequest = false
Documents\file.ini:347:NoRequest = false
Documents\file.ini:387:NoRequest = false
Documents\file.ini:1035:NOREQUEST = true
Documents\file.ini:1047:NoRequest = true
Documents\file.ini:1160:NOREQUEST = true
Documents\file.ini:1242:NOREQUEST = true

This is what I want to get:

PS> $FileContents
false
false
false
false
true
true
true
true

I've tried piping the code into a Select-Object -Last 1 solution, but since my variable is an array it selects the last line in the array, not the last word of each line. I've also thought of just taking the array and doing a "foreach line in the array, cut everything off except the last word". I'm guessing that would work, but it seems like it would be a clumsy solution. I'm sure there's a simple and effective solution to this, but I'm just not seeing it.


Solution

  • You could use -split on the string and grab the last result:

    Select-String -Path "C:\Users\me\Documents\file.ini" -Pattern "NoRequest" |ForEach-Object {
        -split $_.Line |Select-Object -Last 1
    }