【问题标题】:How to filter objects using -notcontains in Powershell [duplicate]如何在Powershell中使用-notcontains过滤对象[重复]
【发布时间】:2022-01-24 14:40:09
【问题描述】:

我正在尝试过滤路径中不包含字符串 "C: \ Windows" 的对象,但过滤不适用于 $_.PathName 参数。

function unquotedPath {
    $unquotedPaths = Get-WmiObject -Class Win32_Service | Where-Object {$_.StartMode -eq "Auto"  -and $_.PathName -notcontains "C:\WINDOWS\"} | Select-Object -Property Name,DisplayName,PathName,StartMode | Out-String
    foreach ($unquotedPath in $unquotedPaths) {
        Write-Host $unquotedPath -ForegroundColor Green
    }
    
}

【问题讨论】:

  • -notcontains 是一个集合运算符。见stackoverflow.com/questions/18877580/…
  • | Out-String 使其成为单个字符串对象...
  • 我使用 Out-String 来获得更好的输出格式,它不会改变过滤方式
  • 简而言之:-contains / -notcontains集合运算符:它们测试 LHS 对象是否完全等于与 RHS 的至少一个元素收藏。不要将它们与.Contains() .NET 方法 用于子字符串匹配 混淆。虽然 PowerShell 没有用于 literal 子字符串匹配的等效运算符,但您可以将 -like通配符表达式-match正则表达式 一起使用,两者都可以其中不区分大小写。
  • 关闭与Out-String 的切线:@iRon 想说的是$unquotedPaths 将收到一个 single (多行)输出字符串跨越所有过滤对象,因此您的 foreach` 循环将被输入(最多)一次。省略循环并改用Write-Host $unquotedPaths -ForegroundColor Green 会产生相同的效果。

标签: powershell


【解决方案1】:

-notcontains 是一个集合运算符。 查看有用的帖子:PowerShell and the -contains operator

你可以使用:

Get-WmiObject -Class Win32_Service | Where-Object {$_.StartMode -eq "Auto" -and !$_.PathName.Contains('C:\WINDOWS\')} 

【讨论】:

  • 该链接很有帮助-尽管我认为将其作为重复投票的一部分提交就足够了。请注意,.Contains() - 与 PowerShell 的运算符不同 - 区分大小写总是在 Windows PowerShell 中如此,在 PowerShell (Core) 7+ 中默认情况下
  • @mklement0 - 考虑到这一点,注意到了,谢谢。
【解决方案2】:

不要使用-notcontains,而是使用-notlike

Get-WmiObject -Class Win32_Service | Where-Object {$_.StartMode -eq "Auto"  -and $_.PathName -notlike "*C:\WINDOWS\*"}

.. 或-notmatch:

Get-WmiObject -Class Win32_Service | Where-Object {$_.StartMode -eq "Auto"  -and $_.PathName -notmatch "^.*C:\\WINDOWS\\"}

-notcontains 用于检查右侧参数(对象)是否与左侧参数(集合)中的元素之一匹配。查看更多here

-notlike 用于检查元素是否与特定模式不匹配。查看更多here

-notmatch 类似于-notlike,但允许正则表达式,因此它更强大。查看更多here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-06
    • 2018-11-12
    • 2021-06-07
    • 2022-12-17
    • 1970-01-01
    • 2022-11-30
    • 2023-01-02
    • 1970-01-01
    相关资源
    最近更新 更多