Many thanks to @Olaf for the help and knowledge. The complete script I used in case anyone finds it helpful is below:
Variables Already Set from reading a separate .xml file. Sometimes “localhost” may be used so it can be used on multiple machines and some times there will not be a “SVR02” depending on the environment:
$ServiceName=“MyWindowsService”
$Server1=“Localhost”
$Server2=“SVR02”
The Script
Function to get the named service state on all the computers\servers involved. A “scope:” is used to allow it to work in my script, may not be required in this simplified version.
Function Get-ServiceStatus {
param (
$ServiceName,
$Servers
)
$StateList =
Invoke-Command -ComputerName $Servers -ScriptBlock {
Get-Service $ServiceName
}
foreach ($Script:State in $StateList) {
[PSCustomObject]@{
Name = $State.Name
Status = $State.Status
ComputerName = $State.PSComputerName
StartType = $State.StartType
}
}
}
Set the $Servers as an array Servers for flexibility, if required. If "Localhost” is set, convert that to the localhosts actual name.
$Servers = @(
$Server1 -replace "Localhost", "$env:COMPUTERNAME"
$Server2 -replace "Localhost", "$env:COMPUTERNAME"
)
If less servers are added to the array above, make a new array with the actual number of servers set because we can’t have a empty or null value in the array to invoke etc.
$ParsedServers = $Servers.Where({! [string]::IsNullOrWhiteSpace($_)})
Get the services status on the different servers using the new array without any empty or null values, calling the function set above.
$StateBefore = Get-ServiceStatus -ServiceName $ServiceName -Servers $ParsedServers
Stop the Service(s) and output on each server.
foreach ($Script:State in $StateBefore) {
Write-Host “Stopping Service…`t” -NoNewline -ForegroundColor Black
## If state isn’t Stopped on the remote server, Stop it.
If ($State.Status -ne ‘Stopped’) {
Invoke-Command -ComputerName $State.ComputerName -ScriptBlock {
Stop-Service $Using:ServiceName
}
# Get ExecutionStatus of the last operation (*not part of this script so the function is not shown above, but I made a function to get me the success of the output*)
Get-ExecutionStatus $?
} else {
Write-Host "`"$ServiceName`" already stopped!" -ForegroundColor Black
}
}
Starting Broker Servives
foreach ($Script:State in $StateBefore) {
Write-Host “Starting Solver Broker…`t” -NoNewline -ForegroundColor Black
## If state wasn’t Stopped in the first place or should have been started (I.e. Was meant to have automatically started and be running already), Start it on the remote server.
If ($State.Status -ne ‘Stopped’ -or $State.StartType -eq ‘Automatic’) {
Invoke-Command -ComputerName $State.ComputerName -ScriptBlock {
Start-Service $Using:ServiceName
}
# Get ExecutionStatus of the last operation
Get-ExecutionStatus $? (not part of this script so the function is not shown above, but I made a function to get me the success of the output)
} else {
Write-Host "`"$ServiceName`" Not set to run!" -ForegroundColor Black
}
}