1

I'm trying to Start a service using Powershell and using the code below

function CheckServiceStatus {
param($winupdate)
$getservice = Get-Service -Name $winupdate

if($getservice.Status -ne $running){
    stop-service $winupdate
    Start-Service $winupdate 
    Write-output "Starting" $winupdate "service"|out-file "C:\Users\Mani\Desktop\abc.txt"
    Add-Content C:\Users\Mani\Desktop\abc.txt  $getservice.Status
    }
}
Read-Host -Prompt "Press Enter to exit"

#Variables

$winupdate = 'vsoagent.192.Shalem'
$running = 'Running'
CheckServiceStatus $winupdate

I got the following error:

Service 'ABC' cannot be stopped due to the following error: Cannot open ABC service on computer '.'

I found some link here on our forum but couldn't resolve. Please suggest

Shalem
  • 1,366
  • 20
  • 44

1 Answers1

3

If you want to start/stop/etc services, you need elevated privileges (run as Admin). You can still get information about the service, but that's it. If you want to include a more verbose error, include this:

$isadmin = [bool](([System.Security.Principal.WindowsIdentity]::GetCurrent()).groups -match "S-1-5-32-544")
if($isadmin){
   Write-Error "You need elevated privileges to run this script"
   exit(1)
}

...

Rest of your code

Or even better, if you're running Powershell 4.0 or higher (You can get it by checking $PSVersionTable), you can include

#Requires -RunAsAdministrator

At the top of your file, and you won't be able to run it without admin privilages.

tituszban
  • 3,909
  • 1
  • 18
  • 27