【问题标题】:PowerShell script executing batch script on remote server在远程服务器上执行批处理脚本的 PowerShell 脚本
【发布时间】:2017-02-15 06:28:13
【问题描述】:

我正在执行一个在远程服务器上执行批处理脚本的 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
    }
}

【问题讨论】:

    标签: powershell


    【解决方案1】:

    试一试:

    $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
    

    【讨论】:

    • 我尝试使用以下 - $remotereturnvalue=Invoke-Command -ComputerName $DBServer -Authentication NegotiateWithImplicitCredential -ErrorAction Stop -ScriptBlock {$cmd = start-process "cmd.exe" -argumentlist "DbBackupBatch.cmd + $FullBackupPath $CustName" $cmdexitcode = $cmd.Exitcode if ($cmdexitcode -eq 0) { exit 0 } else { exit 1 } }
    【解决方案2】:

    无论您在 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
    

    【讨论】:

    • 感谢您的建议。我按照建议进行了更改,现在可以使用了
    最近更新 更多