【发布时间】:2020-10-13 01:47:43
【问题描述】:
为什么这个脚本会从 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
【问题讨论】:
-
我猜您的脚本是使用不同的代码页保存的。
[可能也是两字节 Unicode 的一部分(我怀疑-within the<->)。确保在系统之间二进制传输脚本(或相关文本文件),不通过文本应用程序将其复制/粘贴为例如电子邮件内容(而是将相关文件附加到电子邮件中)。或者只是在同一个系统上测试它(注意,您可以在同一个系统上同时运行 Windows PowerShell 5.1 和 PowerShell Core 7.x)。 -
作为一种解决方法,我会使用这个正则表达式:
'(?<=\[)[^\[\]]+(?=\])'(结果中不允许有任何[或]) -
感谢 iRon 的建议。我在同一个系统上的两个 shell 中使用了相同的脚本。我最初使用 PowerShell 5.1 在 Windows 上编写脚本,但后来发现它在使用 PowerShell 7.0 的 Linux 上不起作用
标签: regex powershell powershell-7.0