pb.RestartService.psm1

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
function Restart-Service {
    <#
    .SYNOPSIS
       Restarts Specified Windows Service
    .EXAMPLE
        %restart-service computername service name
    #>


[PoshBot.BotCommand(
    CommandName = 'restart-service',
    Aliases = ('rs', 'restart-service')
)]

[cmdletbinding()]
param(
    [parameter(ValueFromRemainingArguments = $true)]
    [string[]]$Arguments
)

$q = $Arguments -split ' '
$remotehost = $q[0]
$servicesplit = $q[1..$q.length]
$service = $servicesplit -join ' '

$status=Invoke-Command -ComputerName $remotehost -ScriptBlock {Get-Service $Using:service}
New-PoshBotCardResponse -Type Normal -Title "Example Usage" -Text "% restart-service (Host) (Full Name of Service)"
if($status.status -eq "Running"){
    Invoke-Command -ComputerName $remotehost -ScriptBlock {Stop-Service $Using:service -Force}
    Invoke-Command -ComputerName $remotehost -ScriptBlock {Start-Service $Using:service}
}else{
    Invoke-Command -ComputerName $remotehost -ScriptBlock {Start-Service $Using:service}
}
    $status=Invoke-Command -ComputerName $remotehost -ScriptBlock {Get-Service $Using:service}

    $fields = @{
        Host = $remotehost
        Status = $status.status
        ServiceName = $status.ServiceName
        StartType = $status.StartType
    }
    New-PoshBotCardResponse -Type Normal -Fields $fields
}

Export-ModuleMember -Function 'Restart-Service'