gpt4 book ai didi

powershell - Powershell在远程计算机中运行Bat文件

转载 作者:行者123 更新时间:2023-12-03 00:37:50 24 4
gpt4 key购买 nike

我修改了我从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)
"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

关于powershell - Powershell在远程计算机中运行Bat文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28105138/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com