So I’m trying to write a script that will stop and set start up type for services. So far what I have works if all the services are present.

$Serv=get-service adobeARMservice, AdobeFlashPlayerUpdateSvc, WinDefend, MpsSvc

$Serv | stop-service -PassThru | Set-Service -StartupType Disabled

Get-Service WinRM | Start-Service -PassThru | Set-Service -StartupType Automatic

So my question is what would be the best way to script this so that if the service isn’t there it will skip it. My thought was setting one variable for windows services and one for each optional services. So if I do that how do I get powershell to skip one if it’s not installed?

6 Spice ups

So I just realized that even though I’m “seeing blood” the script still works. But if anyone is still willing to help me I would appreciate it.

You could implement a try catch for a little bit of error handling.

http://www.vexasoft.com/blogs/powershell/7255220-powershell-tutorial-try-catch-finally-and-error-handling-in-powershell

Interesting thanks for the link

Make an array of the service names you’d like to stop, check if those are present, and change those that are.

$list = "adobeARMservice", "AdobeFlashPlayerUpdateSvc", "WinDefend", "MpsSvc", "DoesNotExist", "AlsoDoesNotExist"
$services = Get-Service
$change = $services | ?{$list -contains $_.name}
$change | stop-service -PassThru | Set-Service -StartupType Disabled
Get-Service WinRM | Start-Service -PassThru | Set-Service -StartupType Automatic

Edit: Another way to check the list (use whichever is more intuitive for you)

$change = $services | ?{$_.name -in $list}
3 Spice ups