forked from 1RedOne/BlogPosts
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Restart-RemoteService.ps1
55 lines (42 loc) · 2.26 KB
/
Restart-RemoteService.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
Function Restart-RemoteService{
[CmdletBinding()]
Param($ComputerName=$env:COMPUTERNAME)
DynamicParam {
# Set the dynamic parameters' name
$ParameterName = 'Service'
# Create the dictionary
$RuntimeParameterDictionary = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary
# Create the collection of attributes
$AttributeCollection = New-Object System.Collections.ObjectModel.Collection[System.Attribute]
# Create and set the parameters' attributes
$ParameterAttribute = New-Object System.Management.Automation.ParameterAttribute
$ParameterAttribute.Mandatory = $true
$ParameterAttribute.Position = 1
# Add the attributes to the attributes collection
$AttributeCollection.Add($ParameterAttribute)
# Generate and set the ValidateSet
$arrSet = Get-WmiObject Win32_Service -ComputerName $computername | select -ExpandProperty Name
$ValidateSetAttribute = New-Object System.Management.Automation.ValidateSetAttribute($arrSet)
# Add the ValidateSet to the attributes collection
$AttributeCollection.Add($ValidateSetAttribute)
# Create and return the dynamic parameter
$RuntimeParameter = New-Object System.Management.Automation.RuntimeDefinedParameter($ParameterName, [string], $AttributeCollection)
$RuntimeParameterDictionary.Add($ParameterName, $RuntimeParameter)
return $RuntimeParameterDictionary
}
begin {
# Bind the parameter to a friendly variable
$Service = $PsBoundParameters[$ParameterName]
}
process {
Write-Debug 'ham'
ForEach($machine in $computername){
write-host "Stopping service $service on host $machine..." -NoNewline
Get-WmiObject -ClassName Win32_Service -ComputerName $machine | Where Name -eq $service | % StopService | Out-Null
write-host "[OK]" -ForegroundColor Cyan
Write-Host "Starting Service $service on host $machine..." -NoNewline
Get-WmiObject -ClassName Win32_Service -ComputerName $machine | Where Name -eq $service | % StartService | Out-Null
write-host "[OK]" -ForegroundColor Cyan
}
}
}