我修改了我从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"
答案 0 :(得分:5)
您将命令行设置为在引号中运行。
Invoke-Command -Session $sessions -ScriptBlock {
param($batfilename)
"cmd.exe /c C:\MD5temp\$batfilename"
} -ArgumentList $batfilename -AsJob
PowerShell只会回显裸字符串,而不是将它们解释为命令并执行它们。您需要使用Invoke-Expression
作为后者:
Invoke-Command -Session $sessions -ScriptBlock {
param($batfilename)
Invoke-Expression "cmd.exe /c C:\MD5temp\$batfilename"
} -ArgumentList $batfilename -AsJob
或(更好)删除引号并(可选)使用调用运算符:
Invoke-Command -Session $sessions -ScriptBlock {
param($batfilename)
& cmd.exe /c "C:\MD5temp\$batfilename"
} -ArgumentList $batfilename -AsJob