powershell $ lastexitcode在运行批处理文件时不起作用

问题描述:

我尝试将bat文件中的exitcode/errorlevel代码导入调用bat文件的powershell脚本中。

Althought的%ERRORLEVEL%为1:

BAT文件

call aCONFIGURATION 
for %%f in (.\createData\*.g.sql) do sqlcmd -b -U %UserName% -P %Password% -S %sqlClonedServer% -d %sqlClonedDatabaseName% -i %%f -r1 1> NUL 
echo %ERRORLEVEL% 

当我在powershellscript做

$ lastexitcode它始终为0,但%ERRORLEVEL%表示1

$build = "c:\my.bat" 
$state = & $build 
Write-Host $LASTEXITCODE 

我拉我的这个废话powershell充满了bug的头发。

我已阅读这些链接,但他们并没有帮助的结果是不同的:

我怎样才能修复$ lastexitcode

+0

你刚才reask同样的问题再次更少....如果你与亲密不同意原因你已经完成了你所需要的。你可以编辑这个问题来解释它为什么不是重复的。 – Matt

+0

旧的问题被删除不是因为它的重复,而是因为它不再需要。这个新问题更进一步,我可以提供的信息。 – Elisabeth

echo %ERRORLEVEL%只写s的错误代码到标准输出,之后批处理文件正常退出。

如果你想在批处理脚本实际上回报退出的错误,使用exit /b [exitcode]

call aCONFIGURATION 
for %%f in (.\createData\*.g.sql) do sqlcmd -b -U %UserName% -P %Password% -S %sqlClonedServer% -d %sqlClonedDatabaseName% -i %%f -r1 1> NUL 
exit /b %ERRORLEVEL% 
+0

你是我的英雄!当脚本以任何方式失败时,这给了suceess和1或-1040304 0。感谢Mathias。 – Elisabeth

+0

可以使用退出/ b%ERRORLEVEL%一次,但是当我有多个sqlcmd调用? – Elisabeth

+0

那么,'%ERRORLEVEL%'将只包含* last *调用的退出代码(很像'$ LASTEXITCODE')。是否“OK”是100%取决于您的使用情况和要求:) –