Home > Software design >  Obtain Administrators On Powershell to CSV file
Obtain Administrators On Powershell to CSV file

Time:05-24

I have been given the task to pull administrator information from different OU groups within active directory. I have been given a PowerShell code to run however always comes back with red errors and takes a long time to throw me a CSV file with nothing in it. I have limited PowerShell experience and any help would be grateful.

$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

CodePudding user response:

You are adding members to an undefined variable $AllMembers.
Apart from that, adding to an array with = is very wasteful, because the entire array needs to be rebuilt completely in memory on each iteration.
Better let PowerShell do the collecting for you:

# 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
  • Related