Search code examples
powershellremotinginvoke-command

netsh not working when run via Invoke-Command


When I run the following locally on a server it works just fine.

$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

But when I try to run it remotely like this it wouldn't work.

$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}

Any suggestions on why this is and how to fix it?


Solution

  • I've finally figured it out. Using Invoke-Expression it now works. here is the working code:

    $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"}