首页 > 解决方案 > 为远程服务器列表运行 IIS Powershell 脚本?

问题描述

我正在尝试从同一域中的 100 多台服务器中提取所有站点和绑定,并在其上运行 IIS(在 txt 文件中已经有这些服务器的列表,因此不需要 AD 搜索)。这是当我远程登录并在服务器本身上运行代码时成功从一台服务器中提取它的代码:

$myObject = @()
{
Foreach ($Site in get-website) 
{ 
   Foreach ($Bind in $Site.bindings.collection) 
   { 
      $myObject+=[pscustomobject]@{serverName = $vm;name=$Site.name;Protocol=$Bind.Protocol;Bindings=$Bind.BindingInformation; path=$Site.physicalPath}
   }
}
} $myObject | export-csv -Path C:\results.csv -NoTypeInformation

我遇到的问题是,当我创建下面列出的 foreach 循环时

$servers = (Get-Content results.txt)
foreach ($vm in $servers)

并在上述脚本的顶部运行它,csv 表只显示我运行它的服务器的站点/绑定的副本,而不是从 txt 文件中列出的每个唯一服务器中提取结果。

从每台服务器获取结果的最佳方法是什么?我通过我的凭据拥有完整的管理员权限,当我登录到服务器时,几乎所有服务器都在运行 Windows 2012。

标签: windowspowershelliisserver

解决方案


Get-Website它本身不支持远程连接,因此您需要使用 PowerShell Remoting 在所有服务器上运行它。像这样的东西:

Invoke-Command -Computer (Get-Content results.txt) `
               -ScriptBlock {
                    Get-Website |
                        ForEach-Object {
                         $site = $_
                         $_.bindings.collection |
                            ForEach-Object {                           
                                [pscustomobject]@{
                                    serverName = $env:COMPUTERNAME
                                    name=$site.Name
                                    Protocol=$_.Protocol
                                    Bindings=$_.BindingInformation
                                    path=$site.PhysicalPath
                                }
                            }
                        }
               } | Export-Csv -Path C:\results.csv -NoTypeInformation

推荐阅读