none
Select-String Groups issue RRS feed

  • Question

  • Hi,

    Could someone please explain the difference between the 2 pieces of code below?

    $line = "18-04-2018 23:20:30 Server Window Start:   23:00:00 on 19-04-2018"
    $value = $line | Select-String -Pattern "Start:\s+(.*?):" | % {$_.matches.groups[1].value}

    $line = "18-04-2018 23:20:30 Server Window Start:   23:00:00 on 19-04-2018"
    $value = [regex]::Match($line,'Start:\s+(.*?):').Groups[1].value

    Both output the same value '23', but on Windows Server 2008 R2, with Powershell V2 installed, de first piece of code fails with an error: Cannot index into a null array. The same piece of code works perfectly fine on Windows Server 2012 and 2016, with Powershell V4 or V5. Is the powershell version the reason for the error, or is it something else?

    Just trying to understand what's going on.

    Thanks

    Thursday, April 19, 2018 8:45 AM

Answers

  • Is the powershell version the reason for the error, or is it something else?
    Yes, PowerShell v2 is the reason for the error. PowerShell v3 introduced syntactic sugar for arrays/collections (see documentation). The PowerShell v2 equivalent would be $_.Matches[0].Groups[1].Value.

    -- Bill Stewart [Bill_Stewart]

    Friday, July 27, 2018 4:27 PM
    Moderator

All replies

  • Nothing.  They are equivalent.  The first uses the wrapper CmdLet.

    See: $line | Select-String -Pattern 'Start:\s+(.*?):' |select -expand matches|select -expand Groups | select value

    and:

    if($line -match 'Start:\s+(.*?):'){$matches[1]}else{'No match'}


    \_(ツ)_/

    Thursday, April 19, 2018 9:11 AM
  • Is the powershell version the reason for the error, or is it something else?
    Yes, PowerShell v2 is the reason for the error. PowerShell v3 introduced syntactic sugar for arrays/collections (see documentation). The PowerShell v2 equivalent would be $_.Matches[0].Groups[1].Value.

    -- Bill Stewart [Bill_Stewart]

    Friday, July 27, 2018 4:27 PM
    Moderator