PowerShell 和 Get-Aduser –in,-contains 运算符无法获得与 –match 运算符相同的正确结果

PowerShell & Get-Aduser the –in, -contains operators not get the correct result as –match operator

我不知道为什么 -in 和 -contains 运算符无法获得与 -match 运算符相同的正确结果。

下面是代码。

  $user = @( "sysmon","srvctableau","ParkerE", "NguyenDi")
    
    $depart = get-aduser -filter "enabled -eq 'false'" -properties * |  Select -Property SamAccountName
    
    ForEach ($item in $user) 
    {
        if ($item -in $depart) { Write-Output "-in $item  departed" }
        else{ Write-Output "-in $item  is employee" }   
    } 
    
    ForEach ($item in $user) 
    {
        if ($depart -contains $item) { Write-Output " -contains $item  departed" }
        else{ Write-Output "-contains $item  is employee" } 
    } 
    
    ForEach ($item in $user) 
    {
        if ($depart -match $item) { Write-Output "-match $item  departed" }
        else{ Write-Output "-match $item  is employee" }    
    } 

sysmon 是员工, srvctableau 是员工, 帕克E走了, NguyenDi 出发

谢谢!

-in-contains 是用于检查 value 是否存在于 collection 的运算符,在这种情况下,您正在比较 object[] value.

您可以这样做:

$depart = (Get-ADUser -filter "enabled -eq 'false'").sAMAccountName

# OR

$depart = Get-ADUser -filter "enabled -eq 'false'" |
          Select-Object -ExpandProperty sAMAccountName

或者这个:

if ($item -in $depart.sAMAccountName){ ... }

# AND

if ($depart.sAMAccountName -contains $item){ ... }

这里有一个示例,说明您正在尝试做什么以及失败的原因:

PS /> $test = 'one','two','three' | foreach { [pscustomobject]@{Value = $_} }

PS /> $test

Value
-----
one  
two  
three

PS /> $test -contains 'one'
False

PS /> 'one' -in $test
False

PS /> $test.GetType()

IsPublic IsSerial Name                                     BaseType                                                                                                       
-------- -------- ----                                     --------                                                                                                       
True     True     Object[]                                 System.Array                                                                                                   

PS /> $test.Value -contains 'one'
True

PS /> 'one' -in $test.Value
True