无法从远程服务器列表中获取应用程序池。循环不工作

Unable to fetch application pools from list of remote servers. Looping isnt working

有人可以帮我解决这个问题吗?!?

以下是我正在使用的 ps 脚本,用于从远程计算机获取应用程序池详细信息。

在同一台机器上尝试或逐行执行脚本时有效。

作为脚本文件执行时不工作。然后它在整个输出中显示脚本来自的服务器的应用程序池详细信息运行。

回显正确显示主机名及其循环。但是我不确定为什么脚本没有循环。

请看一下,让我知道如何进一步尝试...


$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
}

读取主机"Press Enter"


Enter-PSSession 仅用于创建交互式会话。它不像您在脚本中期望的那样工作。脚本 运行 仅在您启动它的会话中,在本例中是在本地计算机上。

远程 运行 命令的方法是使用 Invoke-Command。您可以修改脚本以将 Enter-PSSession 更改为 New-PSSession,并且 运行 每个命令使用 Invoke-Command

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

但这效率很低。 Invoke-Command 采用一个脚本块,而不仅仅是一个命令,因此将所有命令放入一个块并在每台计算机上只调用一次 Invoke-Command 是有意义的。完成后,甚至没有任何理由保留 $session 变量。相反,使用 -ComputerName 参数,Invoke-Command 将自动创建一个临时 PSSession。

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

这种方法效果很好,而且非常通用,但如果需要,您甚至不需要手动迭代计算机。相反,将完整的 $nodes 数组传递给 -ComputerName 参数。

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

Invoke-Command 将 运行 列表中所有计算机上的脚本块。