Pregunta

I am trying to start my service with powershell but currently it fails. I don't know why it fails but that is not the point here. When trying to start the host all I don't get the correct exit code so my automatic deploy fails silently.

What I'm trying to do is:

$cmd = "$folder" + "\MyService.exe"
try
{
    & $cmd stop
    & $cmd uninstall
    & $cmd install
    & $cmd start
}
catch
{
    Write-Host "Error: Update of service failed"
    exit 1
}

The start command fails with the following messge:

Topshelf.Hosts.StartHost Error: 0 : The service failed to start., System.InvalidOperationException: Cannot start service MyService on computer '.'. ---> System.ComponentModel.Win32Exception: The service cannot be started, either because it is disabled or because it has no enabled devices associated with it
    --- End of inner exception stack trace ---
    at System.ServiceProcess.ServiceController.Start(String[] args)
    at System.ServiceProcess.ServiceController.Start()
    at Topshelf.Runtime.Windows.WindowsHostEnvironment.StartService(String serviceName)
    at Topshelf.Hosts.StartHost.Run()

and I never get into the catch statement of my powershell script.

UPDATE:

Note that I am asking for how to get the method to the catch statement and not the solution to the actual exception. I have solved the actual exception but I want better feedback in the future if it fails, and that is want the catch statement to be executed which it isn't in case of error.

¿Fue útil?

Solución

try/catch in PowerShell doesn't work with exe. After myservice.exe calls you need to check the automatic variable $LastExitCode. Try something like this:

$out = & $cmd start
if ($LastExitCode -ne 0) # if exe returns 0 on success, if not change the condition accordingly
{
    "ERROR: $out"
    return # to exit script or do something else.
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top