Daniel
Daniel

Reputation: 590

Audit Local User Accounts on Remote Servers

I'm attempting to conduct an audit of local user accounts for all servers in our environment. I'm running into an issue where the output is divided into separate tables for each device, which is not going to work for thousands of devices! It should just be one large table without repeated headers or spaces in between. Once this is run, it will be exported to CSV for further analysis.

Example:

Computer Name Enabled PasswordChangeableDate PasswordExpires UserMayChangePassword
Device 1 Administrator False 2/27/2021 5:00:05 AM True
Device 1 DefaultAccount False True
Device 1 Guest False False
Device 1 WDAGUtilityAccount False 1/24/2020 7:30:01 PM 4/22/2020 8:30:01 PM True
Device 1 WindowsHelp True 2/27/2021 5:00:05 AM True
Device 1 WindowsQuery True 2/27/2021 5:00:05 AM 5/27/2021 6:00:05 AM True
Computer Name Enabled PasswordChangeableDate PasswordExpires UserMayChangePassword
Device 2 Administrator False 2/27/2021 5:00:05 AM True
Device 2 DefaultAccount False True
Device 2 Guest False False
Device 2 WDAGUtilityAccount False 1/24/2020 7:30:01 PM 4/22/2020 8:30:01 PM True
Device 2 WindowsHelp True 2/27/2021 5:00:05 AM True
Device 2 WindowsQuery True 2/27/2021 5:00:05 AM 5/27/2021 6:00:05 AM True

Code Snippit:

foreach ($device in Get-Content "list.txt"){
    Invoke-Command -ComputerName $device -ScriptBlock{
        get-localuser | select @{N="Computer"; E={$env:COMPUTERNAME}}, Name, Enabled, PasswordChangeableDate, PasswordExpires, UserMayChangePassword, PasswordRequired, PasswordLastSet, LastLogon | ft -a
    }  
}

My questions are:

  1. How can I correct this to combine the output into one table?
  2. Is there a better way of doing this? (I'd certainly hope so!)

Upvotes: 1

Views: 1622

Answers (1)

Olaf
Olaf

Reputation: 5232

This should be enough I think:

$Result = 
Invoke-Command -ComputerName (Get-Content "list.txt") -ScriptBlock {
    Get-LocalUser | 
        Select-Object -Property PSComputerName, Name, Enabled, PasswordChangeableDate, PasswordExpires, UserMayChangePassword, PasswordRequired, PasswordLastSet, LastLogon 
}
$Result | Format-Table -AutoSize

The parameter -ComputerName can take an array of computernames. You don't need a loop for that.

You should not use format cmdlets like Format-Table inside a loop. Especially when you plan further steps with the collected data. Collect all needed information first - maybe save them in a variable and just when you output them to the console you can use format cmdlets. Now if you want to output the collected data to a CSV file you can do something like this.

$Result | Export-Csv -Path LocalUserList.csv -NotypeInformation -Delimiter ','

Upvotes: 2

Related Questions