Search code examples
powershellinvoke-command

Powershell Invoke-Command query


I'm scripting a task to remotely restart some server application pools periodically. I'm using Invoke-Command as follows:

Invoke-Command -ComputerName $server {Restart-WebItem "IIS:\AppPools\DefaultAppPool"}

and this works just fine; however, if I parameterize the app pool as follows

$appPool = "IIS:\AppPools\DefaultAppPool"
Invoke-Command -ComputerName $server {Restart-WebItem $appPool}

it fails with

Unexpected object type.
Parameter name: pspath

I assume this is just a syntax issue, but I can't work out what.


Solution

  • on the remote host $appPool will not exist. If you're using PS V3 you can prefix your variable with using: keyword ->

    $appPool = "IIS:\AppPools\DefaultAppPool"
    Invoke-Command -ComputerName $server {Restart-WebItem $using:appPool}
    

    prior to version 3, you had to use the -argumentList parameter