0

为什么这个脚本会从 Powershell v5.1 到 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"

如果我将其剥离为仅将字符串管道传输到提取代码,则它可以工作:

("09:52:04 [INFO] [turpie] <-> ServerConnector [lobby] has connected" | Select-String '(?<=\[)[^]]+(?=\])' -AllMatches).Matches.Groups[1..2].Value
4

1 回答 1

0

事实证明,该行中返回了 MatchInfo 对象:

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

Powershell 版本之间的处理方式不同。

我通过指定该 MatchInfo 对象的 Line 属性避免了这个问题。

$user, $server = ($m.Line | Out-String | Select-String -Pattern '(?<=\[)[^]]+(?=\])' -AllMatches).Matches.Groups[1..2].Value
于 2020-06-23T07:14:45.630 回答