Once again, the fine forum members at ScriptingAnswers.com come through and help get my PowerShell idea engine revving. The latest post posed this basic question: “I need to query my servers and find all services using a specific service account.” The poster thought this would be a good opportunity to learn PowerShell and I wholeheartedly agree. Here’s my approach.
ManageEngine ADManager Plus - Download Free Trial
Exclusive offer on ADManager Plus for US and UK regions. Claim now!
First off, the Get-Service cmdlet can’t help, even though in PowerShell v2 it can connect to remote computers. The problem is that the .NET service object which the cmdlet uses knows nothing about the startup account. But WMI does.
If you query a service using WMI, there is a property called StartName. Normally this will be something like LocalSystem. But sometimes you need to use a custom domain account. That’s what the question is all about. I’ll use LocalSystem as the accountname for demonstration purposes. Using Get-WMIObject we can filter for the account.
PS C:\> get-wmiobject win32_service -filter "startname='localsystem'" | Select Displayname
Displayname
-----------
Active Directory Web Services
Application Experience Lookup Service
Application Management
Windows Audio
Background Intelligent Transfer Service
Computer Browser
...
Obviously I’ve truncated the output. Running through a list of servers to find the appropriate services isn’t much more difficult. I’ll put the list of servers to query in a text file and have a pretty simple PowerShell one-liner.
PS C:\> get-wmiobject win32_service -filter "startname='LocalSystem'" -computer (get-content computers.txt) | Select SystemName,Name,Displayname,State,StartMode
Of course if you want other service properties you can add them. You could sort or filter further. My original suggestion was to export the output to a csv file.
PS C:\> get-wmiobject win32_service -filter "startname='LocalSystem'" -computer (get-content computers.txt) | Select SystemName,Name,Displayname,State,StartMode | Export-CSV servicereport.csv
That way he could open the CSV file in Excel and massage the data anyway he liked. Although you could do a lot of it in PowerShell as well. But also by saving the output to a file, he can use it later when it comes time to changing the password for all those services.
I love examples like this. In VBScript, to go through a list of servers, use WMI to get the service information and save the ouput to a CSV file would easily be a 10-15 line script. Plus you’d have to create the script file, save it and then run it. Compared to typing a one-line PowerShell expression which takes a fraction of the time to develop. Which would you rather do?
Jeff,
Thanks! This is just what I was looking for. I’ll buy your book and study it.
Brandon Forest