我有这个函数可以获得AD安全组及其嵌套成员
Import-Module ActiveDirectory
$GroupList = @{}
$Table = @()
$Record = @{
"Group Name" = ""
"Name" = ""
"nested" = ""
"domain" = ""
}
function Get-GroupHierarchy {
Param(
[Parameter(Mandatory=$true)]
[String]$searchGroup
)
$groupMember = Get-ADGroupMember $searchGroup |
Select name, samaccountname, distinguishedName, objectClass
$username = $groupMember.samaccountname
$distinguishedName = $groupMember.distinguishedName
$dc = [regex]::Match($distinguishedName,'DC=([^,|$]+)').Groups[1].Value
$domainuser = '{0}\{1}' -f $dc, $username
$Record."Group Name" = $searchGroup
$Record."Name" = $groupMember.samaccountname
$Record."nested" = $groupMember.objectclass
$Record."Domain" = $domainuser
$objRecord = New-Object PSObject -Property $Record
$Table += [array]$objrecord
foreach ($member in $groupMember) {
Write-Host $Table $member.objectclass,":", $member.name;
if (!($GroupList.ContainsKey($member.name) {
if ($member.ObjectClass -eq "group") {
$GroupList.add($member.name,$member.name)
$indent += "`t"
Get-GroupHierarchy $member.name
$indent = "`t" * >> ($indent.length - 1)
}
} else {
$member.name
}
}
}
我运行下面的代码来调用函数并管道多个组
$list = Import-Csv C:\temp\ad1.csv
foreach ($group in $list) {
Get-GroupHierarchy $group.name
}
非常适合在主机中打印,但当我尝试导出到CSV时,它无法正常工作。我尝试使用Export-Csv
,ConvertTo-Csv
和Out-File
更新要导管为CSV的函数。什么都行不通,我甚至试图将结果保存到$result
,然后导出外部函数不起作用。
$result = Get-GroupHierarchy $group.name
$result | ConvertTo-Csv c:\temp\test.csv