我正在学习powershell,并希望查询一对AD组并确定用户是否是AD组的成员。
在网上搜索,发现了一些山雀和小块。我知道Active Directory模块,但是避免使用它,因为这个脚本将由非技术用户执行,并且避免为此安装RSAT。
我有Powershell版本2和Windows 7
group1是AD组,有10个嵌套的AD组。
Write-Host "Fetching information from groups.Please wait.."
Add-Type -AssemblyName System.DirectoryServices.AccountManagement
$ct = [System.DirectoryServices.AccountManagement.ContextType]::Domain
$group=[System.DirectoryServices.AccountManagement.GroupPrincipal]::FindByIdentity ($ct,'group1')
$group1 = $group.GetMembers | Where {$_.StructuralObjectClass -eq "group"} | Select SamAccountName
$group1 = $group1 -replace("=", " ") -replace("{", " ") -replace("@", " ") -replace ("}", " ") -replace("SamAccountname", " ") -replace '\s+', ' '
$ADGroups = foreach ($l in group1) {$l.trim()}
确保程序提取AD组信息或退出脚本
if (($ADgroups | out-string) -like $null) {
Write-Host "Unable to fetch AD groups information" -foreground "red"
Start-sleep 10
break
}
可以写入文件的临时位置
$location = "C:\AD"
$ct = [System.DirectoryServices.AccountManagement.ContextType]::Domain
$user = [System.DirectoryServices.AccountManagement.UserPrincipal]::FindByIdentity($ct, $username)
If ($user -like $null) {
Write-host "User does not exist in AD" -foreground "magenta"
start-sleep 10
break
}
Write-Host "Please wait...Looking user group membership..."
$usergroups = $user.GetGroups()
删除文件(如果存在)。
Remove-Item $location\useradgroups.txt
$usergroups | select SamAccountName | Out-File $location\useradgroups.txt -append
$testr = gc $location\useradgroups.txt
if (($testr | out-string) -like $null) {
Write-Host "Unable to fetch user AD groups information" -foreground "red"
Start-sleep 10
Remove-Item $location\useradgroups.txt
break
}
$useradgroups = foreach ($l in $testr ) {$l.trim()}
$useradgroups | Select-String -Pattern "\w" | out-file $location\useradgroups.txt
$useradgroups = gc $location\useradgroups.txt
问题:
除非我修剪输出,否则无法比较。所以必须编写如上所示的脚本:
-replace("=", " ") -replace("{", " ")
Powershell专家的任何建议都会受到欢迎。这对我的学习过程有帮助
答案 0 :(得分:0)
未经测试,但你不能在第1部分使用这样的东西吗?
Import-Module ActiveDirectory
Get-ADGroupMember "group1" | select sAMAccountName
答案 1 :(得分:0)
那么你想要做的是递归获取ADGroupMembers?有点像this或this?总有不止一种方法可以做。 You can use the [ASDI]
type accelerator
$groups = [adsi]'LDAP://CN=GroupName,OU=Groups,OU=Place,DC=Tomorrow,DC=Today'
$group | Get-Member
foreach($group in $groups){
$members = $group.member
foreach($member in $members){
#Is this a group or a user?
#If group Get the Group members
#If a user say the user is part of the group
}
}
您是否尝试格式化用户的distinguishedName?
$user = "CN=Huck Finn,OU=Users,OU=Today,OU=Tomorrow,DC=Yesterday,DC=com"
$splits = ($user -split ',')
[PSCustomObject]@{Username=$splits[0].substring(3);OUPath=($splits[1..($splits.Count-1)] | % {$_.substring(3)}) -join '\'}
希望我帮助过。