Skip to content

Instantly share code, notes, and snippets.

@brettmillerb
Last active October 12, 2018 20:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brettmillerb/c18355dd9320fdf2c4abadb06d685cb7 to your computer and use it in GitHub Desktop.
Save brettmillerb/c18355dd9320fdf2c4abadb06d685cb7 to your computer and use it in GitHub Desktop.
# Define an array of services
$services = 'service1','service2','service3','service4'
# Iterate through each item in the array
foreach ($service in $services) {
# Get the service and save it to the variable
$serviceObj = Get-Service -Name $service
# if the variable is present - An If statement returns a bool value
if ($serviceObj) {
# Stop the service
Stop-Service -Name $serviceObj
}
else {
"Service can not be stopped"
}
}
# Reverses the order of the array
[array]::reverse($services)
# Iterate through the reversed services array stopping the services
foreach ($service in $services) {
$serviceObj = Get-Service -Name $service
if ($serviceObj) {
Stop-Service -Name $service
}
}
# Declare function which can be loaded into session
function Stop-AppServices {
[cmdletbinding()]
Param (
[Parameter(Mandatory = $true,
Position = 0)]
[string[]]
$service
)
foreach ($item in $services) {
try {
$serviceObj = Get-Service -Name $item -ErrorAction Stop
if ($serviceObj) {
Stop-Service -Name $service
}
}
catch {
throw $_.exception.message
}
}
}
# Usage of the function
Stop-AppServices -Service $serviceArr
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment