powershell - 如何在 Powershell 中循环访问 Active Directory 组成员

标签 powershell for-loop active-directory-group

我正在尝试列出包含来自特定 OU 的成员的所有组。为此,我正在读取包含所有组名称列表的文件,并使用 get-ADGroupMember $groupName 查找每个组的成员。我正在将每个成员的值转换为字符串并与 $member.indexOf("specific OU") 进行比较。问题是,我还没有弄清楚如何获得 $member[$i].indexOf("specific OU")。我的代码如下。

编辑:如果我使用 for-each 循环,我可以正确循环成员,但我不能使用中断,这可以防止重复。

Import-Module ActiveDirectory
#declaring end result group array
$results = @()

#sets path for files
$pathName = $MyInvocation.MyCommand.Path
$pathLen = $pathName.LastIndexOf("\")
$pathStr = $PathName.Substring(0,$pathLen +1)
$APgroupFile = $pathStr + "APGroups.csv"
$groupFile = $pathStr + "GGroups.csv"

#gets the list of group names and loops through them
get-content $groupFile | foreach-object{
#sets all of the group names
#start of if1 
if($_.IndexOf("CN=") -ge 0){
$nameStart = $_.IndexOf("CN=")+3
$nameEnd = $_.indexOf(",")-$nameStart
$name = $_.substring($nameStart, $nameEnd)

#issue starts here
#goal is to find member of "specific OU".
#If found, add group to $results.  If not, go to next group
$members = get-ADGroupMember -Identity $name
if($members.length -gt 0){
$i=0
for($i=0; $i -le ($members.length -1); $i++){
#need to check users OU for specific OU.  If a user is member, save group to .txt.  If none are members, move to next group
    $OU = $members.toString()
    if($OU.indexOf("OU=specific OU") -ge 0){#start of if OU
    $results += New-Object psObject -Property @{'GroupName'=$name; 'Member'=$OU}
    break
    }#end if OU
    }#end for mem.length
}#end if mem.length
}#end if1
}#end foreach

$results | Export-Csv $APgroupFile -NoTypeInformation

最佳答案

尝试这个:

Get-ADGroupMember -Identity $name |
Where-Object {$_.distinguishedName -like '*OU=specific OU*'}

关于powershell - 如何在 Powershell 中循环访问 Active Directory 组成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12353922/

相关文章:

PowerShell 脚本在通过任务计划程序运行时缺乏一致性,我是不是遗漏了什么或者这个 Windows 就是 Windows?

R循环创建新文件夹

javascript - 如何用 lodash 重构这个双循环?

c# - 为什么 Principal.IsMemberOf() 对某些组返回假阴性?

powershell - 使用 Powershell 获取所有 AD 用户的递归组成员身份

c# - 根据 AD 组检查用户登录

powershell - New-SelfSignedCertificate -CertStoreLocation 找不到路径

winforms - 使用 powershell 安装时显示自定义消息

c - C 中的反转字符

powershell - 如何将标题添加到现有变量