我正在执行PowerShell脚本,该脚本在远程服务器上执行批处理脚本。但是在PowerShell脚本中,我无法处理批处理脚本中可能发生的任何故障。批处理脚本最后有exit %ERROR_CODE%
。
请告诉我如何在调用PowerShell脚本中捕获批处理脚本中发生的任何错误。
我的PowerShell脚本如下:
$DBServer = $args[0]
$CustName = $args[1]
$FullBackupPath = $args[2]
$command = "cmd.exe /c DbBackupBatch.cmd " + $FullBackupPath + " " + $CustName
$script = 'Invoke-Expression -Command "' + $command + '"'
$scriptblock = [scriptblock]::Create($script)
try {
Invoke-Command -ComputerName $DBServer -Authentication NegotiateWithImplicitCredential -ErrorAction Stop -ScriptBlock $scriptblock
exit 0
} catch {
$message = $_.Exception.Message
Write-Host $_.Exception.Message
# While executing a Java programs, we get message as below -
# Picked up JAVA_TOOL_OPTIONS: -Xms512m -Xmx512m
# This message is treated as error message by PowerShell, though it is not an error
if (($message.Length -lt 50) -and ($message.Contains('Picked up JAVA_TOOL_OPTIONS:'))) {
exit 0
} else {
Write-Host $_.Exception.Message
exit 1
}
}
答案 0 :(得分:0)
给它一个旋转:
$remoteReturnValue = Invoke-Command -ComputerName "DV1IMPSSDB01" -Authentication NegotiateWithImplicitCredential -ScriptBlock {
$cmd = Start-Process "cmd.exe" -Wait -PassThru -ArgumentList "/c timeout 5"
$cmdExitCode = $cmd.ExitCode
if ($cmdExitCode -eq 0) {
return "Success"
}
else {
return "Wuh-oh, we have had a problem... exit code: $cmdExitCode"
}
}
Write-Host $remoteReturnValue -ForegroundColor Magenta
答案 1 :(得分:0)
无论您在PowerShell中尝试做什么,Invoke-Expression
实际上总是错误的做法。 PowerShell可以单独执行批处理文件,因此您可以直接运行DbBackupBatch.cmd
,而无需Invoke-Expression
甚至不cmd /c
。
尝试这样的事情:
$DBServer = $args[0]
$CustName = $args[1]
$FullBackupPath = $args[2]
try {
Invoke-Command -ComputerName $DBServer -ScriptBlock {
$output = & DbBackupBatch.cmd $args[0] $args[1] 2>&1
if ($LastExitCode -ne 0) { throw $output }
} -ArgumentList $FullBackupPath, $CustName -Authentication NegotiateWithImplicitCredential
} catch {
Write-Host $_.Exception.Message
exit 1
}
exit 0