【问题标题】:ForEach-Loop with multiple arrays具有多个数组的 ForEach-Loop
【发布时间】:2019-10-28 02:23:40
【问题描述】:

我目前从我们的 Active Directory 中有 4 个具有不同组织单位名称的数组。

所以我做了一个大的评估,为了不为每个数组创建一个单独的 ForEach 循环(因为这就像 400 行代码)我想把整个事情放到一个循环中。

但是,我需要知道何时运行哪个数组,以便我可以通过 IF 查询在某些位置更改该数组的某些内容。

这是因为并非所有数组都能以这种方式使用代码,例如,必须为每个数组更改 Active Directory 查询的搜索库。

在这里,我创建了一个示例并在 cmets 中描述了我的问题。 ()




$OU1="1-Users","2-Users","3-Users"
$OU2="1-Computers","2-Computers","3-Computers"
$OU3="1-ServiceAccounts","2-ServiceAccounts","3-ServiceAccounts"

foreach ($ou in $OU1 <#AND OU2,OU3#> ){

if($OU1,$OU2 <#= active#> ){

 <# if this array is active - do this code #>
 $SearchBase = "OU="+$ou+",OU=SUBOU,DC=intra,DC=lan"

}

if($OU3 <#= active#>){

 <# if this array is active - do this code #>
$SearchBase = "OU="+$ou+",DC=intra,DC=lan"

}


 <# do this code for all #>

}

我希望你能理解我的意思,并能帮助我解决我的问题。谢谢。

【问题讨论】:

  • 抱歉,我不太明白您的代码试图做什么或您的问题是什么。你为什么要这样跑AD?你想做什么?
  • 您可以遍历列表列表,然后遍历较小列表的内容。此外,您可以使用 splat 将特定值添加到您在查询中使用的属性。查看Get-Help about_Splatting,了解如何构造参数哈希表,您可以在调用 cmdlet 之前根据需要添加/删除/更改值。

标签: powershell foreach active-directory


【解决方案1】:

Lee_Dailey 的意思是:首先使用正确的设置创建一个哈希表,然后对其进行迭代:

$ouList = @(
    @{ "SearchBase" = "OU=SUBOU,DC=intra,DC=lan"; "OUs" = @("1-Users","2-Users","3-Users") },
    @{ "SearchBase" = "OU=SUBOU,DC=intra,DC=lan"; "OUs" = @("1-Computers","2-Computers","3-Computers") },
    @{ "SearchBase" = "DC=intra,DC=lan";          "OUs" = @("1-ServiceAccounts","2-ServiceAccounts","3-ServiceAccounts") }
)

foreach ($item in $ouList)
{
    foreach ($ou in $item.OUs)
    {
        $searchBase = "OU=" + $ou + "," + $item.SearchBase
    }
}

【讨论】:

  • 我接受了另一个建议 (AdminOfThings)。但这也有效。谢谢。
  • 好的,但请注意,当两个列表中都存在 OU 名称时,该解决方案将不起作用
【解决方案2】:

一种方法是将数组附加到表达式中(使用+)。这将有效地创建一个集合,然后您可以使用 -in 运算符来查找匹配项。

$OU1="1-Users","2-Users","3-Users"
$OU2="1-Computers","2-Computers","3-Computers"
$OU3="1-ServiceAccounts","2-ServiceAccounts","3-ServiceAccounts"

foreach ($ou in $OU1+$OU2+$OU3 ){

    if( $ou -in $OU1+$OU2 ){

       <# if this array is active - do this code #>
       $SearchBase = "OU="+$ou+",OU=SUBOU,DC=intra,DC=lan"

    }

    if ($ou -in $OU3){

       <# if this array is active - do this code #>
       $SearchBase = "OU="+$ou+",DC=intra,DC=lan"

    }

    <# do this code for all #>

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-10
    • 2014-10-01
    • 2011-09-18
    • 2019-10-25
    • 2022-11-26
    • 1970-01-01
    • 2017-06-18
    相关资源
    最近更新 更多