Skip to main content
 首页 » 编程设计

powershell之如何在一个 foreach 循环中使用 2 个条件

2025年01月19日26bonelee

我有一个脚本片段。这为我提供了一个包含 2 个属性的数组:Account 和 AccessRights。现在我想构建一个 foreach 循环,但我还需要将第二个值存储在一个变量中以供进一步使用。

如果我这样做:

foreach ($id in $ACLFile.Account) { 
    # do stuff 
} 

我只在 $id 中保存了 Account 属性。但是我怎样才能同时获得它的 AccessRights 值呢?

$ACLFile = GetNTFSAccess | select Account, AccessRights 
$ACLGroup = $ACLFile | Group-Object Account 
$Singles = $ACLGroup.Where({$_.Count -eq 1}).Group 
$Duplicates = $ACLGroup.Where({$_.Count -gt 1}) 
$ItemizedDuplicates = $Duplicates | foreach { 
    [PSCustomObject][ordered]@{ 
        "Account"=$_.Group.Account[0]; 
        "AccessRights" = $_.Group.AccessRights -join ", " 
    } 
} 
@($ItemizedDuplicates, $Singles) 

请您参考如下方法:

遍历对象而不仅仅是一个属性。

foreach ($acl in $ACLFile) { 
    $id     = $acl.Account 
    $access = $acl.AccessRights 
    # ... 
}