Search code examples
powershellvariablesiispowershell-remotinginvoke-command

Pass Varibles read from file to invoke-command


I'm struggling to remotely recycle all IIS app pools with powershell with the word "Test" in the name, but ALSO exclude a couple of specific AppPools with Test in the name. I can do it locally with:

## List of Apppool Names to Exclude
$Exclusions = Get-Content "C:\temp\Recycle TEST app pools Exclusions.txt"

## Load IIS module:
Import-Module WebAdministration

## Restart app pools with test in the name
Get-ChildItem –Path IIS:\AppPools -Exclude $Exclusions | WHERE { $_.Name -like "*test*" } | restart-WebAppPool}

However I can't get it to exclude the app pools from the list when I use:

$server = 'SERVER01', 'SERVER02'

## List of Apppool Names to Exclude
$Exclusions = Get-Content "C:\temp\Recycle TEST app pools Exclusions.txt"

## Load IIS module:
Import-Module WebAdministration

## Restart app pools with test in the name
invoke-command -computername $server -ScriptBlock {Get-ChildItem –Path IIS:\AppPools -Exclude $args[0] | WHERE { $_.Name -like "*test*" } | restart-WebAppPool}} -ArgumentList $Exclusions

The file "C:\temp\Recycle TEST app pools Exclusions.txt" does exist on the remote computer , but also does it need to? Can the list be passed in to the Invoke-Command also if it can be got to work?

Thanks in advance


Solution

  • While passing arrays as a single parameter can be difficult, you can take advantage of it here because you only have one argument type anyway.

    invoke-command -computername $server -ScriptBlock {Get-ChildItem –Path IIS:\AppPools -Exclude $args[0] | WHERE { $_.Name -like "*test*" } | restart-WebAppPool}} -ArgumentList $Exclusions
    

    In this, you use $args[0], but this is equivalent to $Exclusions[0] because all items in the array have been passed as arguments.

    But if they've all been passed as arguments... that's what $args is. So use it exactly as you used $Exclusions locally.

    Invoke-Command `
      -ComputerName $server `
      -ArgumentList $Exclusions `
      -ScriptBlock {
        Get-ChildItem –Path "IIS:\AppPools" -Exclude $args |
          Where-Object Name -like "*test*" |
          Restart-WebAppPool
      }