确定 Powershell 命令是否成功
您好,我对 Powershell 很陌生,但我有一个棘手的问题。我希望能够判断命令是否已成功完成,以便我可以向主机提供有意义的消息。
我正在使用 appcmd
命令在 IIS 中添加绑定。本质上如下:
./appcmd set site /site.name:........................
但如何才能我进行检查以确保其成功与否?
我想,如果我只是在该语句之后添加 Write-Host "Successively linked binding"
,那么无论 appcmd
是否成功,它都会触发。
我猜我需要做类似的事情:
$successful = ./appcmd set site /site.name:....................... .
但是 $successful
似乎是包含 msg 结果的字符串?
感谢对此的任何帮助!干杯
Hi I am quite new to Powershell but I have one niggling question. I want to be able to tell if a command has completed successfully so I can give meaningful messages to host.
I am using the appcmd
command to add a binding in IIS. Essentially that goes as follows:
./appcmd set site /site.name:........................
But how can I do a check to ensure it was successful or not?
I think if I just put Write-Host "Successfully added binding"
after that statement it will fire after regardless if the appcmd
was successful.
I'm guessing I need to do something like:
$successful = ./appcmd set site /site.name:........................
but then $successful
seems to be a string containing the msg result?
Grateful any help on this! Cheers
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
假设appcmd是一个控制台exe,即使出错,脚本中的下一行也会执行。
如果您想测试 EXE 是否出错并且 EXE 使用标准 0 退出代码来指示成功,则只需在调用 EXE 后立即检查
$?
特殊变量即可。如果为 $true,则 EXE 返回 0 退出代码。如果 EXE 在成功返回的退出代码方面不标准(可能有多个成功代码),则检查
$LastExitCode
以获取最后一个 EXE 返回的确切退出代码。Assuming appcmd is a console exe, even if it errors, the next line in the script will execute.
If you want to test if the EXE errored and the EXE uses the standard 0 exit code to indicate success, then just inspect the
$?
special variable right after calling the EXE. If it is $true, then the EXE returned a 0 exit code.If the EXE is non-standard in terms of the exit code it returns for success (perhaps it has multiple success codes) then inspect
$LastExitCode
to get the exact exit code the last EXE returned.