Musings on code and life

Start and Stop remote Windows Services with PowerShell

I am currently working on writing our build scripts in LinqPad and was looking into ways to start and stop Windows Services on a remote machine. I couldn't find a native way in C# so I looked into PowerShell remoting and it seemed to work out.


#StopService.ps1
param (
   [string]$serviceName = $(throw "-serviceName is required."),
   [string]$serverName = $(throw "-serverName is required."),
   [string]$username = $(throw "-username is required."),
   [string]$password = $(throw "-password is required.")
)

function Main() {
     StopService $serviceName
}

function StopService() {
    Execute @($serviceName) {
        param ($serviceName)
        $svc = Get-Service $serviceName
        Write-Host "Stop:" $svc.ServiceName
        if ($svc.Status -ne 'Stopped') {
            $svc.Stop()
            $svc.WaitForStatus('Stopped','00:00:05')
        }
        Write-Host "Stopped:" $svc.ServiceName
    }
}

function Execute([Object[]] $prms, [ScriptBlock] $sb) {

    $securePassword = $password | ConvertTo-SecureString -AsPlainText -Force
    $credential = new-object -typename System.Management.Automation.PSCredential -argumentlist $username,$securePassword
     $uri = "http://" + $serverName + ":5985/WSMAN"

    Invoke-Command -ConnectionUri $uri -Credential $credential -ScriptBlock $sb -ArgumentList $prms
}

Main

#StartService.ps1
param (
   [string]$serviceName = $(throw "-serviceName is required."),
   [string]$serverName = $(throw "-serverName is required."),
   [string]$username = $(throw "-username is required."),
   [string]$password = $(throw "-password is required.")
)

function Main() {
     StartService $serviceName
}

function StartService() {
    Execute @($serviceName) {
        param ($serviceName)
        $svc = Get-Service $serviceName
        Write-Host "Start:" $svc.ServiceName
        if ($svc.Status -ne 'Running') {
            $svc.Start()
            $svc.WaitForStatus('Running','00:00:05')
        }
        Write-Host "Running:" $serviceName
    }
}

function Execute([Object[]] $prms, [ScriptBlock] $sb) {

    $securePassword = $password | ConvertTo-SecureString -AsPlainText -Force
    $credential = new-object -typename System.Management.Automation.PSCredential -argumentlist $username,$securePassword
     $uri = "http://" + $serverName + ":5985/WSMAN"

    Invoke-Command -ConnectionUri $uri -Credential $credential -ScriptBlock $sb -ArgumentList $prms
}

Main