获取 Powershell 上的管理员到 CSV 文件

Obtain Administrators On Powershell to CSV file

我的任务是从活动目录中的不同 OU 组中提取管理员信息。我已经获得了 运行 的 PowerShell 代码,但是返回时总是出现红色错误,并且花了很长时间才给我一个没有任何内容的 CSV 文件。我的 PowerShell 经验有限,如有任何帮助将不胜感激。

$GPComputers = Get-ADComputer -SearchBase "OU=OU=,DC=,DC=Local" -Filter * | where {Test-Connection -ComputerName $_.DNSHostName -count 1 -ErrorAction SilentlyContinue} $GPComputers | % { $a = $_ $Members = Invoke-Command -ComputerName $a.DNSHostname -ScriptBlock{Get-LocalGroupMember -Name 'Administrators'} $AllMembers += $Members $Members = $null } $AllMembers | export-csv c:\temp\LocalAdmins.csv -NoType

您正在向未定义的变量添加成员 $AllMembers
除此之外,使用 += 添加到数组非常浪费,因为 整个 数组需要在每次迭代时在内存中完全重建。
最好让 PowerShell 为您收集:

# set the credentials for admin access on the servers
$cred    = Get-Credential 'Please enter your admin credentials'

$GPComputers = Get-ADComputer -SearchBase "OU=OU=,DC=,DC=Local" -Filter * 
$AllMembers = $GPComputers | ForEach-Object { 
    if (Test-Connection -ComputerName $_.DNSHostName -Count 1 -ErrorAction SilentlyContinue) {
        # simply output the result with added 'ComputerName' property ro be collected in variable '$AllMembers'
        Invoke-Command -ComputerName $_.DNSHostname -Credential $cred -ScriptBlock {
            Get-LocalGroupMember -Name 'Administrators' |
            Select-Object *, @{Name = 'ComputerName'; Expression = {$env:COMPUTERNAME}}
        }
    }
    else {
        Write-Warning "Computer '$($_.DNSHostName)' is not responding"
    }
} 

# remove the extra properties PowerShell added and save to CSV
$AllMembers | Select-Object * -ExcludeProperty PS*, RunSpaceId | Export-Csv -Path 'c:\temp\LocalAdmins.csv' -NoTypeInformation