【问题标题】:Difference between Powershell 5.1 and 7.0 for logging and regex filtering [duplicate]用于日志记录和正则表达式过滤的 Powershell 5.1 和 7.0 之间的区别 [重复]
【发布时间】: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 &lt;-&gt;)。确保在系统之间二进制传输脚本(或相关文本文件),通过文本应用程序将其复制/粘贴为例如电子邮件内容(而是将相关文件附加到电子邮件中)。或者只是在同一个系统上测试它(注意,您可以在同一个系统上同时运行 Windows PowerShell 5.1 和 PowerShell Core 7.x)。
  • 作为一种解决方法,我会使用这个正则表达式:'(?&lt;=\[)[^\[\]]+(?=\])'(结果中不允许有任何[]
  • 感谢 iRon 的建议。我在同一个系统上的两个 shell 中使用了相同的脚本。我最初使用 PowerShell 5.1 在 Windows 上编写脚本,但后来发现它在使用 PowerShell 7.0 的 Linux 上不起作用

标签: regex powershell powershell-7.0


【解决方案1】:

原来是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

【讨论】:

    猜你喜欢
    • 2017-02-04
    • 2012-06-01
    • 2013-09-18
    • 2016-11-18
    • 2012-02-22
    • 2023-04-07
    • 1970-01-01
    • 2013-12-17
    • 1970-01-01
    相关资源
    最近更新 更多