【问题标题】:Executing batch file in the remote machines using powershell as a background job使用 powershell 作为后台作业在远程机器中执行批处理文件
【发布时间】:2016-11-02 04:43:56
【问题描述】:

我要做的就是在远程机器中执行批处理文件作为作业。我在C:\Users\temp文件夹内的所有机器中都有批处理文件。这是我的代码
$batFile = "test.bat" foreach($m in $machine) { Invoke-Command -ComputerName $m -ScriptBlock{param($batFile) & cmd.exe /c "C:\Users\temp\$batFile"} -Authentication negotiate -Credential $cred -ArgumentList $batFile -AsJob }

但我不断得到

管道元素中“&”之后的表达式产生了一个无效的对象。它必须产生一个命令名称,一个脚本 块,或 CommandInfo 对象

我也尝试在 ScriptBlock 中使用 $using:batFile,但没有成功。谁能建议我我可能做错了什么?我正在使用 powershell 版本 4。

【问题讨论】:

  • 我无法复制它,它适用于我在本地计算机上调用 .bat Invoke-Command -ComputerName localhost -ScriptBlock { param($bat) & cmd.exe /c "d:\$bat"} -ArgumentList 't.bat' -AsJob 并且它适用于 & $batcmd $bat 变体。如果你在没有& 的情况下使用-ScriptBlock{param($batFile) cmd.exe /c "C:\Users\temp\$batFile"} 怎么办?
  • 这个问题快把我逼疯了。有没有使用调用命令的替代方法?如果我开始工作,我看不到问题,但是当我在脚本块中传递计算机名时,批处理文件认为我将计算机名作为参数传递给批处理文件...Start-Job -ScriptBlock{cd "C :\Users\temp";cmd.exe /c; & "C:\Users\temp\test.bat" -ComputerName $machineName}
  • 再一次,如果你在没有 & 的情况下使用 -ScriptBlock{param($batFile) cmd.exe /c "C:\Users\temp\$batFile"} 会怎样?你在& 之后得到了什么导致它出错的表达式?
  • 仍然是同样的错误——“& 之后的表达式”,根据您的建议,我什至没有在代码中使用 &。 “invoke-command”是否解释为“&”?
  • 我无法想象发生了什么。 Get-Help about_operators - & 是“调用运算符”或“调用运算符”,它不是 Invoke-Command 的别名。你的 test.bat 脚本中有什么?

标签: powershell powershell-4.0 powershell-remoting


【解决方案1】:

对此进行跟踪,

Invoke-Command -ComputerName $m -ScriptBlock{param($batFile) Trace-Command NativeCommandParameterBinder -Expression { & cmd.exe /c "C:\Users\temp\$batFile"}} -Authentication negotiate -Credential  $cred -ArgumentList $batFile -AsJob

并尝试使用Invoke-Expression 作为解决方法,而不是&

invoke-Expression "cmd.exe /c 'C:\Users\temp\$batFile'"

问候,

Kvprasoon

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-12
    • 1970-01-01
    • 1970-01-01
    • 2023-04-06
    • 1970-01-01
    • 2013-10-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多