2017-02-10 176 views
1

我正在执行一个在远程服务器上执行批处理脚本的PowerShell脚本。但在PowerShell脚本中,我无法处理批处理脚本中可能发生的任何故障。批处理脚本最后有exit %ERROR_CODE%在远程服务器上执行批处理脚本的PowerShell脚本

请让我知道如何捕获调用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

给这个一抡:

$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 
+0

我试着用以下 - $ remotereturnvalue =调用命令-ComputerName $ DBSERVER -Authentication NegotiateWithImplicitCredential -ErrorAction停止-ScriptBlock {$ CMD =启动进程 “的cmd.exe” -ArgumentList “DbBackupBatch.cmd + $ $ FullBackupPath的CustName” $ cmdexitcode = $ cmd.Exitcode 如果($ cmdexitcode -eq 0){ 出口0 } 否则{ 出口1 } } – Himanshu

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 
+0

由于为您的建议。我按照建议和现在的工作做了修改 – Himanshu

+0

@Himanshu不客气。如果您发现它解决了您的问题,请考虑[接受答案](http://meta.stackoverflow.com/a/5235)。 –

相关问题