jason
February 23, 2018, 7:17pm
1
I am passing the name of the service as a parameter. If the service is not running, it should start the service.
I made sure that I have “Unrestricted” execution policy before I ran this function.
I went into the directory where this .PS1 file exists (name of the file is StartWindowsservice.ps1) and ran this as following:
> .\StartWindowsService.ps1 StartWindowsservice ‘FAService’
Nothing happens. It doesn’t write anything to console either.
Any help please?
<pre>
function StartWindowsService{
Param([string] $ServiceName)
$aService = Get-Service -Name $ServiceName
if ($aService.Status -ne "Running"){
Start-Service $ServiceName
Write-Host "Starting " $ServiceName " service"
" Service is now started"
}
if ($aService.Status -eq "running"){
Write-Host "$ServiceName service is already started"
}
}
</pre>
I just tested it out and ran fine…
PS C:\WINDOWS\system32> StartWindowsService -ServiceName "SQLWriter"
SQLWriter service is already started
jason
February 23, 2018, 7:32pm
3
Oh gosh. I don’t know why it is not working for me.
StartWindowsService -ServiceName “SQLWriter”
I am running on windows 8. Is there anything that I should do something different?
> .\StartWindowsService.ps1 StartWindowsservice 'FAService'
If you want to run it as a .ps1, then you have to strip the function part out and the contents of the .ps1 file would be:
Param([string] $ServiceName)
$aService = Get-Service -Name $ServiceName
if ($aService.Status -ne "Running"){
Start-Service $ServiceName
Write-Host "Starting " $ServiceName " service"
" Service is now started"
}
if ($aService.Status -eq "running"){
Write-Host "$ServiceName service is already started"
}
And you would run that like:
.\StartWindowsService.ps1 -ServiceName 'FAService'
Otherwise, leaving it like you have it you have to dot source the file to get access to the function, and you’d have to call it either on two lines or separated by a semicolon like:
. .\StartWindowsService.ps1
StartWindowsservice -ServiceName 'FAService'
#OR
. .\StartWindowsService.ps1; StartWindowsservice -ServiceName 'FAService'
Hi Jason,
Are you running the powershell console as administrator?
Can you try
get-service 'servicename' | start-service
Let us know if that works while the ps console is run as a administrator
Regards
Shihan