Powershell Script to Audit Service Accounts Across All Servers

Today I got a half-joke request from a colleague to write  script to help him audit service accounts across a multitude of servers. Initially, I didn’t see the use of writing a full script to do this for myself and my AD environment so I fired off this from my phone as a quick/dirty version.
tl;dr

$services = foreach($server in $serverlist){
    Get-WmiObject -ComputerName $server win32_service
}

foreach ($service in $services){
    if ($service.startname -ne "localsystem"){
    if ($service.startname -ne "NT AUTHORITYLocalService"){
        write-host $_ | fl -Property name,startname
        }
    }
}

 

Unsurprisingly, since I wrote it in Hangouts while on the subway, it did not work. So I fixed it, and made it a bit more robust and non-my AD specific. All it does is do a WMI based filter of all AD Computers, takes whatever’s got a Windows Server OS installed and adds it to a list. Then it goes through that list, grabs all Windows Services, checks which ones aren’t using one of the BUILTIN service accounts, and outputs the list of all remaining services into a three column list which can be redirected to a text file for Excel processing if needed.

$servers = Get-AdComputer -LDAPFilter "(OperatingSystem=*Server*)"
$serverlist = @()
foreach($server in $servers){$serverlist += $server.name}

foreach($server in $serverlist){
    $services = Get-WmiObject -ComputerName $server win32_service
    foreach($service in $services){
        if ($service.startname -ne "LocalSystem" `
        -And $service.startname -ne "NT AUTHORITY\LocalService" `
        -And $service.startname -ne "NT Authority\NetworkService"){
             $padserver = $server.padright(32)
             $padservicename = $service.name.padright(32)
             write-host $padserver $padservicename $service.startname.padright(32)
                        }
                }
        }

As with all my scripts, this is available on the Scripts page if you feel it’d be useful to you.