0

Why would this script be returning different results from Powershell v5.1 to v7.0

<#
    The intention of my real script is to monitor a log file for certain lines and then send me a notification.
    This test script has been stripped down to just reading the last line of itself, and then trying to process
    the logged message. It should extract the username and server names.
    Under 5.1 it returns "turpie" and "lobby"
    However on v7 it returns "turpie" and "7mServerConnector [lobby".
#>
$sb = [scriptblock]::create("get-content -wait "+ $MyInvocation.MyCommand.Path + " -tail 1")
start-job -ScriptBlock $sb | Out-Null

while (1) { 
  $m = $(Get-Job | Receive-Job | Select-String -SimpleMatch "ServerConnector [lobby] has connected" | Get-Unique) 
  if ($null -ne $m) { 
    Write-Host $m
    $user, $server = ($m | Out-String | Select-String '(?<=\[)[^]]+(?=\])' -AllMatches).Matches.Groups[1..2].Value
    Write-Host $user "has connected to" $server
  }
  Start-Sleep 1 
}

# "09:52:04 [INFO] [turpie] <-> ServerConnector [lobby] has connected"

If I strip it down to just piping the string to the extraction code, it works:

("09:52:04 [INFO] [turpie] <-> ServerConnector [lobby] has connected" | Select-String '(?<=\[)[^]]+(?=\])' -AllMatches).Matches.Groups[1..2].Value
3
  • 1
    I guess your scripts are saved using a different code page. The [ is probably also a part of a two byte Unicode (I suspect the - within the <->). Make sure you binary transfer the script (or the concerned text file) between the systems, do not copy/paste it via a text application as e.g e-mail content (but rather attach the concerned file to the e-mail). Or simply test it on the same system (note that you can run both Windows PowerShell 5.1 and PowerShell Core 7.x on the same system). Commented Jun 23, 2020 at 6:13
  • As a work around , I would use this regex: '(?<=\[)[^\[\]]+(?=\])' (which doesn't allow for any [ or ] in the results) Commented Jun 23, 2020 at 6:30
  • Thanks for the suggestions iRon. I was using the same script in both shells on the same system. I originally wrote the script on Windows using PowerShell 5.1, but then found it wasn't working on Linux using PowerShell 7.0 Commented Jun 23, 2020 at 7:09

1 Answer 1

0

It turns out that the MatchInfo object returned in the line:

$m = $(Get-Job | Receive-Job | Select-String -SimpleMatch "ServerConnector [lobby] has connected" | Get-Unique) 

was being handled differently between Powershell versions.

I avoided the problem by specifying the Line property of that MatchInfo object.

$user, $server = ($m.Line | Out-String | Select-String -Pattern '(?<=\[)[^]]+(?=\])' -AllMatches).Matches.Groups[1..2].Value
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.