Use -notlike to filter out multiple strings in PowerShell

后端 未结 9 502
执念已碎
执念已碎 2020-12-14 15:58

I\'m trying to read the event log for a security audit for all users except two, but is it possible to do that with the -notlike operator?

It\'s somethi

相关标签:
9条回答
  • 2020-12-14 16:13

    Yep, but you have to put the array first in the expression:

    ... | where { @("user1","user2") -notlike $_.username }
    

    -Oisin

    0 讨论(0)
  • 2020-12-14 16:15

    don't use -notLike, -notMatch with Regular-Expression works in one line:

    Get-MailBoxPermission -id newsletter | ? {$_.User -NotMatch "NT-AUTORIT.*|.*-Admins|.*Administrators|.*Manage.*"}
    
    0 讨论(0)
  • Using select-string:

    Get-EventLog Security | where {$_.UserName | select-string -notmatch user1,user2}
    
    0 讨论(0)
  • 2020-12-14 16:22

    V2 at least contains the -username parameter that takes a string[], and supports globbing.

    V1 you want to expand your test like so:

    Get-EventLog Security | ?{$_.UserName -notlike "user1" -and $_.UserName -notlike "*user2"}
    

    Or you could use "-notcontains" on the inline array but this would only work if you can do exact matching on the usernames.

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

    0 讨论(0)
  • 2020-12-14 16:23

    Scenario: List all computers beginning with XX1 but not names where 4th character is L or P

    Get-ADComputer -Filter {(name -like "XX1*")} | Select Name | Where {($_.name -notlike "XX1L*" -and $_.name -notlike "XX1P*")}
    

    You can also count them by enclosing the above script in parens and adding a .count method like so:

    (Get-ADComputer -Filter {(name -like "XX1*")} | Select Name | Where {($_.name -notlike "XX1L*" -and $_.name -notlike "XX1P*")}).count
    
    0 讨论(0)
  • 2020-12-14 16:24

    I think Peter has the right idea. I would use a regular expression for this along with the -notmatch operator.

    Get-EventLog Security | ?{$_.Username -notmatch '^user1$|^.*user$'}
    
    0 讨论(0)
提交回复
热议问题