Using Invoke-Command to Get Application Pools on Remote Servers

1.1k views Asked by At

I'm attempting to use Invoke-Command to get a list of application pools on multiple remote servers. So far I have something like:

$servers = Get-Content -Path "C:\Path\to\servers.txt"

$array = New-Object -TypeName 'System.Collections.ArrayList'

foreach ($server in $servers) {
Invoke-Command -ComputerName $server -ScriptBlock {
Import-Module WebAdministration
$sites = Get-ChildItem IIS:\sites
    foreach ($site in $sites) {
        $array.Add($site.bindings)}}}

However I get the error:

 You cannot call a method on a null-valued expression.
    + CategoryInfo          : InvalidOperation: (Add:String) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull
    + PSComputerName        : computername

I've tried using regular arrays instead of ArrayLists and I get the following error:

Method invocation failed because [Microsoft.IIs.PowerShell.Framework.ConfigurationElement] doesn't contain a method named 'op_Addition'.
    + CategoryInfo          : InvalidOperation: (op_Addition:String) [], RuntimeException
    + FullyQualifiedErrorId : MethodNotFound
    + PSComputerName        : computername

Can anyone help point me in the right direction?

1

There are 1 answers

2
TWEESTY On

Your object $arrayis not known on your remote servers. So, one proposition is to send your array to the remote server, then add some values and return it :

$servers = Get-Content -Path "C:\Path\to\servers.txt"    

$array = New-Object -TypeName 'System.Collections.ArrayList'

foreach ($server in $servers) {
    $array = Invoke-Command -ComputerName $server -ScriptBlock {
      param($array)
      Import-Module WebAdministration
      $sites = Get-ChildItem IIS:\sites
      foreach ($site in $sites) {
         [void]($array.Add($site.bindings))
      }
      $array
     } -ArgumentList $array
}