0

我有一个调用 .cmd 文件的 power shell 脚本。这里的架构看起来像

-PowerShell文件代码

$arguments='/savecred /profile /user:myDomain\myuser "cmd /c C:\Users\myuser\code.cmd"' Start-Process cmd.exe $arguments -Wait

  • .cmd 代码文件

这里代码调用 wget 请求来下载文件

wget .....(这里的命令)

我的目标是在 PowerShell 命令提示符下(完成 Start-Process 命令后)了解 wget 命令是否成功执行,或者在执行过程中是否发生了 401、404 等错误。这里我对错误的类型特别不感兴趣,只需要知道是否发生错误。

4

2 回答 2

0

与 Start-Process 一起使用$?是行不通的:

C:\PS> Start-Process cmd.exe -arg '/c exit 5'
C:\PS> $?
True

如果你想使用 Start-Process,你可以走这条路线:

C:\PS> $p = Start-Process cmd.exe -arg '/c exit 5' -PassThru -Wait
C:\PS> $p.ExitCode
5

或者您可以直接调用 cmd.exe:

C:\PS> cmd /c exit 5
C:\PS> $LASTEXITCODE
5

在最后一个示例中,您可以使用$?,但我更喜欢$LastExitCode,因为一些大脑受损的控制台应用程序成功返回非零值。关于调用 cmd.exe 和使用 $LASTEXITCODE 请参阅此ScriptingGuy 博客文章

要获得方便的CheckLastExitCode功能,请查看此博客文章以了解该功能的实现。

于 2013-10-07T23:45:55.233 回答
0

不确定这是否是您要问的,但您可以使用 $ 测试最后一个命令的非零返回码?变量,如果返回码不为零,则为 $false。

假设您有一个 test.cmd 文件,它只返回 5:

exit 5

如果您在 PowerShell 中运行它,您可以查看 $?

if ($?) {"No error"} else {"some error"}

以下是更多信息的链接:http: //blogs.technet.com/b/heyscriptingguy/archive/2011/05/12/powershell-error-handling-and-why-you-should-care.aspx

于 2013-10-07T23:26:28.287 回答