I am trying to get a list of computers that is running a particular service or not. I seem to be missing something I cant wrap around. The output still gives me true even when the service is stopped during a test run. Any help greatly appreciated.
on mobile for now, but Invoke-Command relies on WinRM being running in order to work. Feels like a chicken and egg scenario. Get-service has a -ComputerName parameter where you can run it against a remote computer to check the status of WinRM and I donāt believe it requires it to be running to work.
EDIT: also, you gotta format your code so we can read it. Theres a āPreformatted Textā option in the tool bad or you can wrap your code in 3 back tick characters.
@grey0ut Apologies should look better. Yeah WinRM was just an example, the real service was SEMgrSvc. It would be Stopped and when I run the command I get a true Value.
on the if statement, try specifying the status eq to running or stopped. otherwise test @grey0ut approach with running get-service and adding the computername.
something like this should work to check the status
if ((get-service -Name WinRM).Status -eq 'running' ){
write-host "service is running"
}
else {
write-host "service is stopped"
}
Ok Iām back on a computer and thought I would look at this again. One thing I would change is that youāre using Invoke-Command to then run Get-Service against a remote computername, so weāre remotely invoking a command that does stuff remotely. Itās redundant and I donāt know if it would cause problems.
Since Invoke-Command is reliant on WinRM to be working and set up and Get-Service with the -ComputerName parameter isnāt, I think we should just rely on Get-Service.
I also like to try as best I can to only create my output objects in one spot. Meaning instead of āIf this output object like this, else output object like thisā we just gather up all our values ahead of time and create the output object accordingly at the bottom of the loop.
Example:
Notice iāve omitted the $cred variable as Get-Service doesnāt require credentials to operate. Thereās also no reason to get the environment variable for the computername because we already know the computename as itās in our text list weāre working with.
I havenāt tested it but I also used a try/catch block on the service status such that if Get-Service fails to retrieve the service status the value becomes āerrorā instead of just a boolean.
Nice @grey0ut , It ran a little longer than the last one but its more compacted and still output the needed true/false variables. With that said on the $cred. Iāll be trying this in the next few days, I would like to see if this can be retrieve without the $cred to domain computers that require admin credential for remote session.