知道为什么下面的代码不起作用吗?
尝试将用户名和群组导出到 csv。我只需要群组名称。
请帮忙 - 非常感谢
$users = (Get-Content users.txt)
foreach ($user in $users) {
$file = $user.Name + '_ACL'
(Get-ADUser –Identity $user –Properties MemberOf).MemberOf -replace '^CN=([^,]+),OU=.+$','$1' | Export-CSV -path "$file.csv" -NoTypeInformation
}
答案1
我总是使用 Quest AD cmdlet...下面将提取指定搜索根目录中具有成员的所有组..
Add-PSSnapin Quest.ActiveRoles.ADManagement
Connect-QADService
$GroupInfo = '' | Select 'Group Name','Group Samaccountname','Group Description','Member Name','Member Description'
$AllGroups = @()
$MyGroups = Get-QADGroup -SearchRoot "OU...." -DontUseDefaultIncludedProperties -IncludedProperties Name,samaccountname,Description,Member | select Name,samaccountname,Description,Member
foreach($Group in $MyGroups){
$GroupInfo.'Group Name' = $Group.Name
$Groupinfo.'Group Samaccountname' = $Group.Samaccountname
$GroupInfo.'Group Description' = $Group.Description
foreach($Member in $Group.Member){
$User = Get-QADUser $Member -DontUseDefaultIncludedProperties -IncludedProperties Name,samaccountname,Description | select Name,samaccountname,Description
$GroupInfo.'Member Name' = $User.Name
$GroupInfo.'Member Samaccountname' = $User.Samaccountname
$GroupInfo.'Member Description' = $User.Description
#it takes a while to go through a lot of goups...this just lets you watch so you don't think it's broke and cancel it.
$GroupInfo | select 'Group Name','Group Samaccountname','Group Description','Member Name','Member Samaccountname','Member Description'
$AllGroups += $GroupInfo | Select 'Group Name','Group Samaccountname','Group Description','Member Name','Member Samaccountname','Member Description'
}
}
$AllGroups | Export-Csv Groups_w_members.csv -NoTypeInformation #Export all that group info to csv file.
答案2
为此(Get-ADUser –Identity $user –Properties MemberOf).MemberOf
,请尝试使用Get-ADUser –Identity $user –Properties MemberOf | Select-Object -ExpandProperty MemberOf
。
$users = (Get-Content users.txt)
不需要引号,并且 Import-Csv 提供的结果比 Get-Content 更好。CSV 的第一行提供属性名称。因此,$users = Import-Csv users.csv
。
'^CN=([^,]+),OU=.+$','$1'
其中的 $1 是什么?它似乎没有定义。除非它是正则表达式的一部分。如果它是某种变量,单引号将阻止它被求值。
另外,请考虑:
$users = Import-Csv users.csv
foreach ($user in $users) {
$currentUser = Get-ADUser $user -Properties MemberOf
$groups = $currentUser | Select-Object -ExpandProperty MemberOf
foreach ($group in $Groups) {
$groupName = Get-ADGroup $group | select name
# do something here with a collection to collect the groupnames
}
# do something here with a custom object
# to collect the properties from user and groups
# using a custom object named $customUser
$customUser | Export-Csv -NoTypeInformation -Append export.csv
}