我的任务是从活动目录中的不同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:tempLocalAdmins.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:tempLocalAdmins.csv' -NoTypeInformation