我在Power Shell方面采取了行动以帮助日常管理,我认为编写一个脚本将很有趣:
足够简单吧?
我在互联网上做了一些类似项目的搜索,并且能够整理出几乎可以满足我需要的脚本。
## Search for all the groups and store them in $ADGroupList[]
$ADGroupList = Get-ADGroup -Filter * -Properties * -SearchBase "OU=Security Groups,OU=Users,DC=company,DC=local" |
Select Name -ExpandProperty Name |
Sort
## Look at each element and do a couple things
$AdGroupList = @(foreach ($Group in $ADGroupList) {
## Object to store each group name and their memberships
[PSCustomObject]@{
GroupName = $Group.Name
Members = Get-ADGroupMember -Identity $Group |
Select SamAccountName -ExpandProperty SamAccountName
}
})
## Save all the created objects to the CSV
$AdGroupList | Export-Csv -Path C:\scripts\AdGroupList.csv
有了脚本,我得到了
#TYPE System.Management.Automation.PSCustomObject "GroupName","Members" "group1","ad_user" "group2","System.Object[]" "group3","System.Object[]" "group4","ad_user" "group5","System.Object[]" ...
如您所见,只有1个成员的组以纯文本形式显示该用户。
但是,具有更多成员的较大组将改为显示System.Object[]
。
多做一些尝试,我尝试了一些尝试,通过修改Export.CSV来扩展sys.obj。
$AdGroupList |
Select-Object Server, @{Expression={$_.Members.Name -join ';'}} |
Export-Csv -Path C:\scripts\AdGroupList.csv
但这并没有显示任何有用的信息,因为它仅对创建的对象有效,我无法确定如何深入研究每个项目。
我还尝试创建一个嵌套的forloop来输出对象中的每个samaccountname并将其添加到要显示的对象中。
但是,由于语法错误,我无法使其正常工作。对于用户,我不确定需要使用什么变量来等效于$group
……我尝试过$user
,$samaccountname
和$name
。
foreach($Group in $ADGroupList) {
[PSCustomObject]@{
GroupName = $Group.Name
$MembersList = Get-ADGroupMember -Identity $Group |
Select SamAccountName -ExpandProperty SamAccountName
foreach ($Name in $MembersList) {
Members = $SamAccountName.SamAccountName
}
}
}
我在这里想念什么?我真的很喜欢PS可以给我的工具,但我似乎无法完全弄清楚。
答案 0 :(得分:0)
哈希表无法像您尝试的那样工作。更改
[PSCustomObject]@{
GroupName = $Group.Name
$MembersList = Get-ADGroupMember -Identity $Group |
Select SamAccountName -ExpandProperty SamAccountName
foreach ($Name in $MembersList) {
Members = $SamAccountName.SamAccountName
}
}
进入
[PSCustomObject]@{
GroupName = $Group.Name
Members = (Get-ADGroupMember -Identity $Group |
Select-Object -Expand SamAccountName) -join ','
}