使用-notlike在PowerShell中过滤掉多个字符串

Pas*_*cal 26 powershell

我正在尝试读取事件日志以获取除两个用户之外的所有用户的安全审核,但是可以通过-notlike运营商执行此操作吗?

它是这样的:

Get-EventLog -LogName Security | where {$_.UserName -notlike @("*user1","*user2")}
Run Code Online (Sandbox Code Playgroud)

我让它适用于单个用户,例如:

Get-EventLog -LogName Security | where {$_.UserName -notlike "*user1"}
Run Code Online (Sandbox Code Playgroud)

sli*_*sec 34

V2至少包含-username带字符串[] 的参数,并支持globbing.

V1你想扩展你的测试,如下所示:

Get-EventLog Security | ?{$_.UserName -notlike "user1" -and $_.UserName -notlike "*user2"}
Run Code Online (Sandbox Code Playgroud)

或者您可以在内联数组中使用"-notcontains",但这只有在您可以对用户名进行精确匹配时才有效.

... | ?{@("user1","user2") -notcontains $_.username}

  • 您还可以通过变量引用要过滤的用户名列表: ?{$users -notcontains $_.username} (2认同)

小智 10

我认为彼得有正确的想法.我会使用正则表达式和-notmatch运算符.

Get-EventLog Security | ?{$_.Username -notmatch '^user1$|^.*user$'}
Run Code Online (Sandbox Code Playgroud)


Jos*_*osh 7

为了支持"匹配任何..."场景,我创建了一个非常容易阅读的函数.我的版本有很多,因为它是一个PowerShell 2.0 cmdlet,但我在下面粘贴的版本应该在1.0中工作并且没有多余的装饰.

你这样称呼它:

Get-Process | Where-Match Company -Like '*VMWare*','*Microsoft*'
Get-Process | Where-Match Company -Regex '^Microsoft.*'

filter Where-Match($Selector,[String[]]$Like,[String[]]$Regex) {

    if ($Selector -is [String]) { $Value = $_.$Selector }
    elseif ($Selector -is [ScriptBlock]) { $Value = &$Selector }
    else { throw 'Selector must be a ScriptBlock or property name' }

    if ($Like.Length) {
        foreach ($Pattern in $Like) {
            if ($Value -like $Pattern) { return $_ }
        }
    }

    if ($Regex.Length) {
        foreach ($Pattern in $Regex) {
            if ($Value -match $Pattern) { return $_ }
        }
    }

}

filter Where-NotMatch($Selector,[String[]]$Like,[String[]]$Regex) {

    if ($Selector -is [String]) { $Value = $_.$Selector }
    elseif ($Selector -is [ScriptBlock]) { $Value = &$Selector }
    else { throw 'Selector must be a ScriptBlock or property name' }

    if ($Like.Length) {
        foreach ($Pattern in $Like) {
            if ($Value -like $Pattern) { return }
        }
    }

    if ($Regex.Length) {
        foreach ($Pattern in $Regex) {
            if ($Value -match $Pattern) { return }
        }
    }

    return $_

}
Run Code Online (Sandbox Code Playgroud)


小智 6

不要使用 -notLike、-notMatch 与正则表达式在一行中工作:

Get-MailBoxPermission -id newsletter | ? {$_.User -NotMatch "NT-AUTORIT.*|.*-Admins|.*Administrators|.*Manage.*"}
Run Code Online (Sandbox Code Playgroud)