您的代码没有任何问题,尽管我可能会像这样简化它:
$path = "c:\test\test.txt"
$fileMissing = -not (Test-Path -LiteralPath $path)
$msg = if ($fileMissing) {'file does not exist'} else {'file exists'}
Write-Host $msg
exit ([int]$fileMissing * 2)
您的问题很可能与您执行脚本的方式有关。如果您使用-Command
参数运行脚本,如下所示:
powershell.exe -Command "&{& 'C:\path\to\your.ps1'}"
或像这样:
cmd /c echo C:\path\to\your.ps1 | powershell.exe -Command -
如果发生错误,则返回值为 1,否则为 0,无论您设置什么退出代码。
要让 PowerShell 返回正确的退出代码,您需要exit $LASTEXITCODE
在命令字符串中添加一个:
powershell.exe -Command "&{& 'C:\path\to\your.ps1'; exit $LASTEXITCODE}"
-File
或使用参数调用脚本:
powershell.exe -File "C:\path\to\your.ps1"