通过Invoke-Command运行时netsh无法正常工作

时间:2018-04-26 11:07:33

标签: powershell remoting invoke-command

当我在服务器上本地运行以下内容时,它可以正常工作。

$NetshArgumentList = 'advfirewall firewall add rule name="Zabbix Agent" dir=in action=allow program="C:\zabbix\bin\win64\zabbix_agentd.exe" enable=yes'
Start-Process -FilePath 'netsh' -ArgumentList $NetshArgumentList

但是,当我尝试像这样远程运行它时,它将不起作用。

$ComputerName = 'Remote-Host'
$NetshArgumentList = 'advfirewall firewall add rule name="Zabbix Agent" dir=in action=allow program="C:\zabbix\bin\win64\zabbix_agentd.exe" enable=yes'
Invoke-Command -ComputerName $ComputerName -ScriptBlock {Start-Process -FilePath 'netsh' -ArgumentList $using:NetshArgumentList}

关于为什么会这样做以及如何解决它的任何建议?

2 个答案:

答案 0 :(得分:0)

$NetshArgumentList在远程会话中不可见。您可以要求PowerShell使用using: scope modifier

复制它
$ComputerName = 'Remote-Host'
    $NetshArgumentList = 'advfirewall firewall add rule name="Zabbix Agent" dir=in action=allow program="C:\zabbix\bin\win64\zabbix_agentd.exe" enable=yes'
    Invoke-Command -ComputerName $ComputerName -ScriptBlock {Start-Process -FilePath 'netsh' -ArgumentList $using:NetshArgumentList}

答案 1 :(得分:0)

我终于明白了。使用Invoke-Expression它现在有效。这是工作代码:

$ComputerName = 'Remote-Host'
$NetshArgumentList = 'advfirewall firewall add rule name="Zabbix Agent" dir=in action=allow program="C:\zabbix\bin\win64\zabbix_agentd.exe" enable=yes'
Invoke-Command -ComputerName $ComputerName -ScriptBlock {Invoke-Expression "netsh $using:NetshArgumentList"}