Try the following
# Define list of server names and services
$ServerName = Get-Content "C:\User\desktop\ServerList"
$ServiceList = @("Service1", "Service2")
foreach ($Server in $ServerName) {
# Check if the server is reachable
if (Test-Connection -ComputerName $Server -Quiet) {
foreach ($Service in $ServiceList) {
try {
# Check the status of the service on the remote server
$ServiceStatus = Get-Service -ComputerName $Server -Name $Service
# If the service is not running, attempt to start it
if ($ServiceStatus.Status -ne "Running") {
Write-Host "Service $Service on Server $Server is not running. Attempting to start..."
# Start the service remotely using Invoke-Command
Invoke-Command -ComputerName $Server -ScriptBlock {
param($ServiceName)
# Start the service
Start-Service -Name $ServiceName
} -ArgumentList $Service
} else {
Write-Host "Service $Service on Server $Server is already running."
}
} catch {
Write-Host "Error checking or starting service $Service on Server $Server: $_"
}
}
} else {
Write-Host "Server $Server is not reachable."
}
}
If the above response helps answer your question, remember to "Accept Answer" so that others in the community facing similar issues can easily find the solution. Your contribution is highly appreciated.
hth