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

Lui*_*Liu 1 powershell batch-file

I modified a function I got from Microsoft forum, it purpose is to run copy a bat file to a remote machine and to run it there. I could see the file being copied over, however it seems not working when I try to call the Invoke-Command to execute the file. Any advice will be appreciated, thank you :)

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" 
Run Code Online (Sandbox Code Playgroud)

Ans*_*ers 5

你把你试图在引号中运行的命令行.

Invoke-Command -Session $sessions -ScriptBlock {
  param($batfilename)
  "cmd.exe /c C:\MD5temp\$batfilename"
} -ArgumentList $batfilename -AsJob
Run Code Online (Sandbox Code Playgroud)

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

Invoke-Command -Session $sessions -ScriptBlock {
  param($batfilename)
  Invoke-Expression "cmd.exe /c C:\MD5temp\$batfilename"
} -ArgumentList $batfilename -AsJob
Run Code Online (Sandbox Code Playgroud)

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

Invoke-Command -Session $sessions -ScriptBlock {
  param($batfilename)
  & cmd.exe /c "C:\MD5temp\$batfilename"
} -ArgumentList $batfilename -AsJob
Run Code Online (Sandbox Code Playgroud)