Unable to fetch application pools from list of rem

2019-07-27 22:23发布

问题:

Can someone please help me on this.!?

Following is the ps script that i am working with to fetch application pool details from a remote machine.

It works when tried on the same machine or when the script is executed line by line.

It isnt working when it is executed as a script file. Then it shows the application pool details of the server from which the script is running throughout its output.

The echo is showing hostnames and its looping correctly. But i am not sure why the script isnt looping.

Please have a look and let me know how to try this further...


$nodes = Get-Content "C:\PowerShell\Servers.txt"
foreach($node in $nodes) {
echo $node
Enter-PSSession $node
Import-Module WebAdministration
$webapps = Get-WebApplication
$list = @()
foreach ($webapp in get-childitem IIS:\AppPools\)
{
$name = "IIS:\AppPools\" + $webapp.name
$item = @{}
$item.WebAppName = $webapp.name
$item.Version = (Get-ItemProperty $name managedRuntimeVersion).Value
$item.UserIdentityType = $webapp.processModel.identityType
$item.Username = $webapp.processModel.userName
$obj = New-Object PSObject -Property $item
$list += $obj
}
$list | Format-Table -a -Property "WebAppName", "Version", "State", "UserIdentityType", "Username", "Password"
Exit-PSSession
}

Read-Host "Press Enter"


回答1:

Enter-PSSession is only used to create an interactive session. It doesn't work the way you expect in a script. A script runs only in the session where you launched it, in this case on the local machine.

The way to run commands remotely is with Invoke-Command. You can modify your script to change Enter-PSSession to New-PSSession, and run each command using Invoke-Command

foreach ($node in $nodes) {
  $session = New-PSSession $node
  Invoke-Command -Session $session { $webapps = Get-Webapplication }
  Invoke-Command -Session $session { $list = @() }
  etc...
}

But that's inefficient. Invoke-Command takes a scriptblock, not just one command, so it makes sense to put all of the commands into one block and call Invoke-Command just once per computer. Once you've done that, there's not even any reason to keep the $session variable around. Instead, use the -ComputerName parameter, and Invoke-Command will create a temporary PSSession automatically.

foreach ($node in $nodes) {
  Invoke-Command -Computer $node { 
    Import-Module WebAdministration
    $webapps = Get-WebApplication
    $list = @()
    etc...
  }
}

This method works great and is extremely versatile, but you don't even need to manually iterate over the comptuers if you want. Instead, pass the full $nodes array to the -ComputerName parameter.

$nodes = Get-Content "C:\PowerShell\Servers.txt"
Invoke-Command -Computer $nodes { 
  Import-Module WebAdministration
  $webapps = Get-WebApplication
  $list = @()
  etc...
}

Invoke-Command will run the scriptblock on all of the computers in the list.