我不知道为什么-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" }
} NguyenDi是员工,srvctableau是员工,sysmon已离职,sysmon已离职
谢谢!
发布于 2021-06-13 10:39:25
-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
Truehttps://stackoverflow.com/questions/67954348
复制相似问题