2017-02-10 277 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)。 –