我想在远程机器上运行这样的命令
Invoke-Command -ComputerName $RemoteMachine -Credential $Cred `
-ScriptBlock { echo MYPASS | "C:\Program Files (x86)\AnyDesk\AnyDesk.exe" --set-password}
但是我收到此错误
At C:\Users\user\Desktop\anydesk.ps1:14 char:33
+ ... o MYPASS | "C:\Program Files (x86)\AnyDesk\AnyDesk.exe" --set-pass ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Expressions are only allowed as the first element of a pipeline.
使用管道时指定程序的路径似乎有问题。我该如何修复?
更新:
因为我想在具有多个命令的脚本块中使用它并将变量传递给脚本块,所以以下修改也不起作用。
$NewPassword = 'Mahmood00'
Invoke-Command -ComputerName $RemoteMachine -Credential $Cred -ScriptBlock {
& {
Param(param1)
'echo $param1 | "C:\Program Files (x86)\AnyDesk\AnyDesk.exe" --set-password'
} } ArgumentList = $Using:NewPassword
这有语法问题。如果我使用
$NewPassword = 'Mahmood00'
Invoke-Command -ComputerName $RemoteMachine -Credential $Cred -ScriptBlock {
& Param(param1){
'echo $param1 | "C:\Program Files (x86)\AnyDesk\AnyDesk.exe" --set-password'
} } ArgumentList = $Using:NewPassword
我收到此错误:
A Using variable cannot be retrieved. A Using variable can be used only with Invoke-Command,
更新2:
使用局部变量也不起作用。见下文:
Invoke-Command -ComputerName $RemoteMachine -Credential $Cred -ScriptBlock {
& {
$param1 = $Using:NewPassword
cmd /c 'echo $param1 | "C:\Program Files (x86)\AnyDesk\AnyDesk.exe" --set-password'
} }
密码实际上是 $param1,而不是该变量的值。
答案1
这应该有效:
$NewPassword = 'Mahmood00'
Invoke-Command -ComputerName $RemoteMachine -Credential $Cred -ScriptBlock {
Param($NewPassword)
$Expression = 'echo {0} | "C:\Program Files (x86)\AnyDesk\AnyDesk.exe" --set-password' -f $NewPassword
Start-Process cmd.exe -ArgumentList "/c $Expression"
} -ArgumentList $NewPassword
你不需要$Using:Varname
这个,你可以正常地将它传递给 Scriptblock
答案2
我建议对整个管道执行远程“cmd /c”。要将环境变量从您的计算机传递到远程,请使用参数
ArgumentList
。
未经测试,类似:
Invoke-Command -ComputerName $RemoteMachine -Credential $Cred
-ScriptBlock {
Param ($param1)
'echo $param1 | "C:\Program Files (x86)\AnyDesk\AnyDesk.exe" --set-password'}
ArgumentList = $Using:NewPassword
请参阅文档 调用命令。