PowerShell & Get-Aduser 的 –in, -包含运算符无法获得正确的结果,因为 –match 运算符



我不知道为什么-in-and-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是员工,ParkerE离开,NguyenDi离开

谢谢!

-in-contains是用于检查collection中是否存在value的运算符,在这种情况下,您将比较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

最新更新