-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathStart-ServiceOnRemoteComputer.ps1
69 lines (67 loc) · 2.58 KB
/
Start-ServiceOnRemoteComputer.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
<#
Author: Stan Crider
Date: 12 Sept 2022
Crap: starts and/or restarts a specified service on specified computers
#>
## Variables
# Service name (not display name) of service
$ServiceName = "AGPM Service"
# list of computers to run against
$Computers = @(
"test1.acme.com"
"test2.acme.com"
)
## Script
ForEach($Computer in $Computers){
# Check if computer is online
If(Test-Connection -ComputerName $Computer -Quiet -Count 2){
# Connect to computer and run script
$PSSession = New-PSSession -ComputerName $Computer
Invoke-Command -Session $PSSession -ScriptBlock{
$ErrorMessage = $null
Try{
# Check if service is installed and report status
$ServiceStatus = Get-Service -Name $using:ServiceName -ErrorAction Stop
}
Catch{
$ErrorMessage = "The service $using:ServiceName on $using:Computer does not exist."
}
If($ErrorMessage){
Write-Warning $ErrorMessage
}
Else{
Switch($ServiceStatus.Status){
# Start service if stopped
{$_ -eq "Stopped"}{
Write-Host "The service `"$using:ServiceName`" on $using:Computer is starting..."
Try{
Start-Service -Name $using:ServiceName -ErrorAction Stop
}
Catch{
Write-Warning "The service `"$using:ServiceName`" on $using:Computer failed to start."
}
}
# Restart service if running
{$_ -eq "Running"}{
Write-Host "The service `"$using:ServiceName`" on $using:Computer is restarting..."
Try{
Restart-Service -Name $using:ServiceName -ErrorAction Stop
}
Catch{
Write-Warning "The service `"$using:ServiceName`" on $using:Computer failed to restart."
}
}
# Report status if not stopped or running
Default{
Write-Warning ("The status of service `"$using:ServiceName`" on $using:Computer is: " + $ServiceStatus.Status)
}
}
}
}
# Close connection
Exit-PSSession
}
Else{
Write-Warning "The computer $Computer is not responding to pings. No connection attempt made."
}
}