【问题标题】:-Like, -Match in subarray-like,-匹配子数组
【发布时间】:2019-12-23 20:57:33
【问题描述】:

我正在使用 Search-ADAccount 从 Active Directory 获取非活动用户列表,然后将其传送到 Get-ADUser,以便我可以使用 MemberOf 不包含组 "Accounts_to_Keep" 的位置。我相信我可以使用正确的号码 (379) 和完整的 DN 字符串。但是,如果组移动,我想使用-match-like 来仅使用组的名称。它返回的数字不一样。

如果我使用MemberOf 对单个用户单独执行此操作,它只会过滤掉一个组并返回用户拥有的另一个组,所以我认为这就是为什么我拥有的不仅仅是-contains。有没有办法在没有foreach自己的情况下使用-like-match 作为子数组?

从字符串中删除完整的 DN

PS> $InactiveAll.Count
488
PS> ($InactiveAll | Where {-not $_.memberof.contains("CN=Accounts_to_Keep,OU=DC")}).Count 
379
PS> ($InactiveAll | Where { $_.memberof -notlike "*Accounts_To_keep*"}).Count 
427
PS> ($InactiveAll | Where {-not $_.memberof -contains ("CN=Accounts_to_Keep,OU=DC")}).Count 
61
PS> ($InactiveAll | Where {-not ($_.memberof -contains ("CN=Accounts_to_Keep,OU=DC"))}).Count
379
PS> ($InactiveAll | Where { $_.memberof -notmatch "Accounts_To_Keep"}).Count
427

【问题讨论】:

    标签: powershell active-directory operators contains group-membership


    【解决方案1】:

    -like 和 -notlike 使用通配符,"*"。此外,在组数组上使用 -notlike 和 -notmatch 与在单个元素上使用它们的结果不同。我认为您需要研究这些运营商的工作。任何结果都将在 where-object 中评估为“真”。

    'group1','group2','group3' -notmatch 'group1'
    group2
    group3
    
    
    'group1','group2','group3' -notlike '*group1*'
    group2
    group3
    

    这是一种在字符串数组中搜索子字符串的方法:

    | where { -not ($_.memberof | select-string group1) }
    

    或者

    | where { -not ($_.memberof -match 'group1') }
    | where { -not ($_.memberof -like '*group1*') }
    

    【讨论】:

      【解决方案2】:

      我认为-match 在测试专有名称方面不会比-like 提供任何优势,因为在这种情况下,您知道'CN=Accounts_to_Keep' 将通过名称识别所需的组。不要忘记-notcontains 的存在是为了稍微简化您的代码。

      这段代码可能有点不对劲,因为我前面没有要测试的目录,但如果你想排除该组的成员,无论它可能存在,我认为你应该让 Active Directory 处理寻找小组...

      $groupToExclude = Get-ADGroup -Identity 'Accounts_to_Keep'
      

      ...然后您可以将专有名称作为一个整体来匹配,而不是匹配专有名称子字符串...

      ($InactiveAll | Where { $_.MemberOf -notcontains $groupToExclude.DistinguishedName}).Count
      

      这假定域中只有一个名为 Accounts_to_Keep 的组。如果不能保证这一点,您可以将该组的 objectGUIDobjectSid 传递给 Get-ADGroup,而不是其名称,以准确无误地检索该组。

      【讨论】:

      • 这是一个很好的点,首先从 AD 中获取组,我只是不希望它被硬编码。这解决了这两个问题。谢谢。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多