I’m a Powershell novice and I’ve been working on putting a script together that I can’t seem to get what I want.
I tweaked a script I found online that gives queries Active Directory servers, pings boxes to make sure they are alive and enumerates all “alive” boxes for all services with non-system service accounts. I'm cleaning up stale or not used service accounts in Active Directory and this script would be a great help.
The issue is, I’m stuck in how to get the output to a hash variable to create a nice CSV report I can email the team.
I’ve included the script. Hopefully you can help me out finalize the script. Thanks!
Get the list of servers from Active Directory
$servers = Get-ADComputer -Filter {OperatingSystem -Like "Windows Server"} -Properties *
Set the live computers array
$livecomputers = @()
Create a object to store results
$Report = @()
Check each server to make sure it is up.
foreach ($x in $servers) {
$up = Test-Connection -Count 1 -ComputerName $x.Name -ErrorAction SilentlyContinue
if ( $up -ne $null){ $livecomputers += $x.Name }
}
Main Function – Using WMI, check each service and find any service that is using a non-standard account
foreach ($machine in $livecomputers){
gwmi win32_service -computer $machine | where {$.StartName -ne “LocalSystem”}|where {$.StartName -ne “NT AUTHORITY\LocalService”} | where {$.StartName -ne “NT AUTHORITY\NetworkService”} | `
where {$.StartName -ne “Local System”}|where {$.StartName -ne “NT AUTHORITY\Local Service”} |where {$.StartName -ne “NT AUTHORITY\Network Service”}
}
foreach ($winserv in $getserv) {
# For each service - build a hash containing information
$hash = @{
ComputerName = $winserv.PSComputerName
Service = $winserv.Name
ServiceAccount = $winserv.StartName
}
# Add the hash to a new object
$winservinfo = new-object PSObject -Property $hash
# Store our new object within the report array
$Report += $winservinfo
}
Export our report array to CSV and store as our dynamic file name
$Report | Export-Csv D:\ServiceAccounts.csv -Append -NoTypeInformation