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"
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 changeEnter-PSSession
toNew-PSSession
, and run each command usingInvoke-Command
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 callInvoke-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, andInvoke-Command
will create a temporary PSSession automatically.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.Invoke-Command
will run the scriptblock on all of the computers in the list.