Thursday, 17 July 2014

Power shell - Get remote machine service and manage it (start/stop)

$computername = "REMOTE_COMPUTERNAME"
$spadmin = "REMOTE_USERNAME"
$service = "REMOTE_SERVICE_NAME"
$password = convertto-securestring "REMOTE_PASSWORD" -asplaintext -force
Try
{
    $credential = New-Object -typename System.Management.Automation.PSCredential -argumentlist $spadmin, $password
    $session = New-PSSession -Credential $credential -ComputerName $computername
    $param1 = $service
    $returnValue = Invoke-Command -Session $session -ScriptBlock { Param($param1) $status = (get-service $param1 | where {$_.status -eq 'running'});return $status} -ArgumentList $param1
echo $returnValue;
Invoke-Command -Session $session -ScriptBlock { Param($param1) $status = stop-service $param1;return $status} -ArgumentList $param1
$returnValue = Invoke-Command -Session $session -ScriptBlock { Param($param1) $status = (get-service $param1);return $status} -ArgumentList $param1
echo $returnValue;
    Remove-PSSession -Session $session
}
Catch [Exception]
{
     Write-Host $_.Exception.Message
    [Environment]::Exit(1)
}

No comments:

Post a Comment