Powershell 运行 远程机器中的 Bat 文件

Powershell Run Bat File in Remote machine

我修改了从 Microsoft 论坛获得的一个功能,它的目的是 运行 将 bat 文件复制到远程机器并 运行 它在那里。我可以看到文件正在被复制,但是当我尝试调用 Invoke-Command 来执行文件时它似乎不起作用。任何建议将不胜感激,谢谢 :)

function Run-BatchFile ($computer, [string]$batLocation)
{

    $sessions = New-PSSession -ComputerName $computer -Credential qa\qalab3
    Copy-Item -Path $batLocation -Destination "\$computer\C$\MD5temp" #copy the file locally on the machine where it will be executed
    $batfilename = Split-Path -Path $batLocation -Leaf
    Invoke-Command -Session $sessions -ScriptBlock {param($batfilename) "cmd.exe /c C:\MD5temp$batfilename" } -ArgumentList $batfilename -AsJob
     $remotejob | Wait-Job #wait for the remote job to complete     
    Remove-Item -Path "\$computer\C$\MD5temp$batfilename" -Force #remove the batch file from the remote machine once job done
    Remove-PSSession -Session $sessions #remove the PSSession once it is done
}

Run-BatchFile 192.168.2.207 "D:\MD5Check\test.bat" 

您将尝试 运行 的命令行放在引号中。

Invoke-Command -Session $sessions -ScriptBlock {
  param($batfilename)
  <b>"cmd.exe /c C:\MD5temp$batfilename"</b>
} -ArgumentList $batfilename -AsJob

PowerShell 只会回显裸字符串,不会将它们解释为命令并执行它们。您需要为后者使用 Invoke-Expression

Invoke-Command -Session $sessions -ScriptBlock {
  param($batfilename)
  <b>Invoke-Expression</b> "cmd.exe /c C:\MD5temp$batfilename"
} -ArgumentList $batfilename -AsJob

或(更好)删除引号并(可选)使用调用运算符:

Invoke-Command -Session $sessions -ScriptBlock {
  param($batfilename)
  <b>&</b> cmd.exe /c "C:\MD5temp$batfilename"
} -ArgumentList $batfilename -AsJob