2013-04-09 88 views
3

我想用powershell启动我的服务,但目前失败。我不知道它为什么会失败,但这不是重点。当试图启动主机时,我没有得到正确的退出代码,所以我的自动部署失败了。如何在命令失败时返回错误代码?

我试图做的是:

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

start命令失败,出现以下的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() 

,我从来没有进入我的PowerShell脚本的catch语句。

UPDATE:

请注意,我询问如何获取方法的catch语句,而不是解决实际的异常。我已经解决了实际的异常,但是如果它失败了,我希望在未来有更好的反馈,那就是要执行catch语句,而不是在出错的情况下执行。

回答

3

try/catch在PowerShell中无法使用exe。 经过myservice.exe调用您需要检查自动变量$LastExitCode。 尝试类似这样:

$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. 
} 
+0

我也试过,以及它没有工作。我不认为最后的退出代码设置正确。 – 2013-04-09 10:32:49

+0

但是'$ LastExitCode'在错误之后得到了一些值? – 2013-04-09 10:34:26

+0

'$ LastExitCode'的值被设置为0. – 2013-04-09 10:49:04

相关问题