-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServiceModule.psm1
More file actions
89 lines (85 loc) · 2.75 KB
/
Copy pathServiceModule.psm1
File metadata and controls
89 lines (85 loc) · 2.75 KB
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# Returns ServiceController or $null
# Script will exit for any other exception
function Get-Service_ {
param (
[Parameter(Mandatory=$true)]
[string]$ServiceName
)
try {
return $(Get-Service -Name $ServiceName -ErrorAction Stop)
} catch {
if ($_.Exception.Message -like "Cannot find any service with service name '*'.") {
return $null
} else {
Write-Host "An error occurred in function ""Get-Service_"", exiting with exception message ""$($_.Exception.Message)"""
exit 1
}
}
}
# Returns boolean
function Get-ServiceExists {
param (
[Parameter(Mandatory=$true)]
[string]$ServiceName
)
$service = Get-Service_ -ServiceName $ServiceName
return $null -ne $service
}
# Returns enum type "[System.ServiceProcess.ServiceControllerStatus]" or $null
# Reference: https://learn.microsoft.com/en-us/dotnet/api/system.serviceprocess.servicecontrollerstatus?view=dotnet-plat-ext-8.0#fields
function Get-ServiceStatus {
param (
[Parameter(Mandatory=$true)]
[string]$ServiceName
)
$service = Get-Service_ -ServiceName $ServiceName
if ($null -eq $service) {
return $null
} else {
($service).Status
}
}
# Returns boolean or $null
function Get-ServiceIsRunning {
param (
[Parameter(Mandatory=$true)]
[string]$ServiceName
)
$status = Get-ServiceStatus -ServiceName $ServiceName
if ($null -eq $status) {
return $null
} else {
return $status.Equals([System.ServiceProcess.ServiceControllerStatus]::Running)
}
}
# Returns boolean for whether the service was running after completion, any errors/exceptions are outputted to stdout
function Start-Service_ {
param (
[Parameter(Mandatory=$true)]
[string]$ServiceName
)
$service = Get-Service_ -ServiceName $ServiceName
if ($null -eq $service) {
Write-Host "Service '$ServiceName' does not exist."
return $false
}
if (($service).Status.Equals([System.ServiceProcess.ServiceControllerStatus]::Running)) {
Write-Host "Service '$ServiceName' is already running."
return $true
}
Write-Host "Service '$ServiceName' not running, attempting to start."
try {
Start-Service -ServiceName $ServiceName -ErrorAction Stop
$service.Refresh()
if ($service.Status -eq 'Running') {
Write-Host "Service '$ServiceName' started successfully."
return $true
} else {
Write-Host "Service '$ServiceName' failed to start within the timeout period."
return $false
}
} catch {
Write-Host "Service '$ServiceName' failed to start: $($_.Exception.Message)"
return $false
}
}