我不知道为什么-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