Powershell - 检查安全组成员与另一个列表

时间:2017-05-02 13:11:32

标签: powershell

一些上下文,我试图从安全组中获取用户列表,然后检查这些用户是否中是否有任何已分配的XenDesktop。

请原谅我,我昨天才开始使用Powershell,所以格式化了。它首先抓住AD组中的用户,然后检查该用户是否有分配的桌面,哪个有效,但我似乎无法工作的是,如果在该列表中找到用户,我希望它移动到下一个用户名,而不是继续检查每台机器,然后检查最后的代码位。

$checkusernames = Get-ADGroupMember "***AD security Group***" | Select SamAccountName

$desktops = get-brokerdesktop -DesktopGroupName Personal_WIN8 | Select MachineName, @{Name='AssociatedUserNames';Expression={[string]::join(“;”, ($_.AssociatedUserNames))}}

foreach ($username in $checkusernames.SamAccountName) {
foreach ($desktop in $desktops) {
If ($desktop.AssociatedUserNames -like "*$username*") {
write-host $username "is assigned to" $desktop.machinename
}
write-host $username "is not assigned to a desktop"
}
Write-host $username "is not assigned to anything"
pause
}

1 个答案:

答案 0 :(得分:0)

如果您想提前退出ForEach循环,可以使用Break关键字。例如:

$checkusernames = Get-ADGroupMember "***AD security Group***" | Select SamAccountName

$desktops = get-brokerdesktop -DesktopGroupName Personal_WIN8 | Select MachineName, @{Name='AssociatedUserNames';Expression={[string]::join(“;”, ($_.AssociatedUserNames))}}

foreach ($username in $checkusernames.SamAccountName) {

    $machine = ''

    foreach ($desktop in $desktops) {

        If ($desktop.AssociatedUserNames -like "*$username*") { 
            $machine = $desktop.machinename
            break
        }
    }

    If ($machine) {
        write-host $username "is assigned to" $desktop.machinename
    } Else {
        write-host $username "is not assigned to a desktop"
        pause
    }
}

这将停止内部ForEach循环的当前循环(一旦完成整个循环),而不会中断外部循环的持续循环。

根据评论中的讨论,我还重新组织了代码,以便您只获得一个输出,具体取决于桌面是否与用户匹配,并且只有在找不到匹配项时才会暂停