首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >PowerShell & Get-Aduser -in,-contains运算符作为-match运算符无法获得正确的结果

PowerShell & Get-Aduser -in,-contains运算符作为-match运算符无法获得正确的结果
EN

Stack Overflow用户
提问于 2021-06-13 10:30:34
回答 1查看 58关注 0票数 0

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

下面是代码。

代码语言:javascript
复制
  $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已离职

谢谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-06-13 10:39:25

-in-contains是用于检查value是否存在于collection中的运算符,在本例中,您将比较object[]value

您可以这样做:

代码语言:javascript
复制
$depart = (Get-ADUser -filter "enabled -eq 'false'").sAMAccountName

# OR

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

或者这样:

代码语言:javascript
复制
if ($item -in $depart.sAMAccountName){ ... }

# AND

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

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

代码语言:javascript
复制
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
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67954348

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档