通过PowerShell在远程服务器上运行批处理脚本

时间:2015-08-20 18:39:25

标签: powershell batch-file remote-server

一旦连接,我需要从客户端(与服务器相同的域)连接到某些远程服务器,我需要运行批处理文件:

我已使用此代码完成此操作:

$Username = 'USER'
$Password = 'PASSWORD'
$pass = ConvertTo-SecureString -AsPlainText $Password -Force
$Cred = New-Object System.Management.Automation.PSCredential -ArgumentList $Username,$pass

try {
    Invoke-Command -ComputerName "SERVER1" -Credential $Cred -ScriptBlock -ErrorAction Stop {
        Start-Process "C:\Users\nithi.sundar\Desktop\Test.bat"
    }
} catch {
    Write-Host "error"
}

此脚本不会出现任何错误,但它似乎没有执行批处理脚本。

对此的任何意见都将不胜感激。

2 个答案:

答案 0 :(得分:5)

尝试替换

invoke-command -computername "SERVER1" -credential $Cred -ScriptBlock -ErrorAction stop { Start-Process "C:\Users\nithi.sundar\Desktop\Test.bat" }

Invoke-Command -ComputerName "Server1" -credential $cred -ErrorAction Stop -ScriptBlock {Invoke-Expression -Command:"cmd.exe /c 'C:\Users\nithi.sund
ar\Desktop\Test.bat'"}

答案 1 :(得分:2)

您发布的代码不可能没有错误运行,因为您弄乱了Invoke-Command的参数顺序。这个:

Invoke-Command ... -ScriptBlock -ErrorAction Stop { ... }

实际上应该看起来像这样:

Invoke-Command ... -ErrorAction Stop -ScriptBlock { ... }

此外,请勿为此使用Invoke-Expression。无论您需要完成什么,它都是practically always the wrong tool。您也不需要Start-Process,因为PowerShell可以直接运行批处理脚本:

Invoke-Command -ComputerName "SERVER1" -ScriptBlock {
    C:\Users\nithi.sundar\Desktop\Test.bat
} -Credential $Cred -ErrorAction Stop

如果命令是字符串而不是简单的单词,则需要使用call operator

Invoke-Command -ComputerName "SERVER1" -ScriptBlock {
    & "C:\Users\nithi.sundar\Desktop\Test.bat"
} -Credential $Cred -ErrorAction Stop

您还可以使用cmd.exe调用批处理文件:

Invoke-Command -ComputerName "SERVER1" -ScriptBlock {
    cmd /c "C:\Users\nithi.sundar\Desktop\Test.bat"
} -Credential $Cred -ErrorAction Stop

如果由于某种原因必须使用Start-Process,则应添加参数-NoNewWindow-Wait

Invoke-Command -ComputerName "SERVER1" -ScriptBlock {
    Start-Process 'C:\Users\nithi.sundar\Desktop\Test.bat' -NoNewWindow -Wait
} -Credential $Cred -ErrorAction Stop

默认情况下,Start-Process在单独的窗口中异步运行被调用的进程(即,调用立即返回)。这很可能是您的代码无法按预期运行的原因。