如何使用PowerShell获取IIS的Application Setting属性并筛选符合要求的站点
PowerShell 实现IIS站点健康状态检测方案
前提要求
- 以管理员身份运行PowerShell
- 提前安装并导入
IISAdministration模块,可执行Install-Module IISAdministration完成安装
功能说明
实现读取IIS全部站点的应用程序设置,筛选出MonitoringEnabled = True的站点,逐个发起Web请求校验响应是否包含OK标识,最终将所有站点的健康状态导出为JSON文件保存到C盘health.json路径。
完整可用代码
# 导入IIS管理模块 Import-Module IISAdministration # 初始化健康结果数组 $siteHealthResult = @() # 获取所有IIS站点 $allSites = Get-IISSite foreach ($site in $allSites) { # 读取站点的Application Settings配置 $webConfigPath = Join-Path $site.Applications["/"].VirtualDirectories["/"].PhysicalPath "web.config" if (-not (Test-Path $webConfigPath)) { # 站点无web.config直接跳过 continue } $webConfig = [xml](Get-Content $webConfigPath) $monitoringEnabled = $webConfig.configuration.appSettings.add | Where-Object {$_.key -eq "MonitoringEnabled"} | Select-Object -ExpandProperty value -ErrorAction SilentlyContinue # 筛选监控开启的站点 if ($monitoringEnabled -ne "True") { continue } # 取站点第一个HTTP/HTTPS绑定的地址构造请求URL $binding = $site.Bindings | Where-Object {$_.Protocol -in "http","https"} | Select-Object -First 1 if (-not $binding) { $siteHealthResult += @{ SiteName = $site.Name Healthy = "False" Remark = "无可用HTTP/HTTPS绑定" } continue } $bindingInfo = $binding.BindingInformation.Split(':') $requestUrl = "$($binding.Protocol)://$($bindingInfo[2])$(if($bindingInfo[1] -ne '80' -and $bindingInfo[1] -ne '443'){":$($bindingInfo[1])"})" # 发起Web请求校验响应 try { $response = Invoke-WebRequest -Uri $requestUrl -UseBasicParsing -TimeoutSec 10 $healthStatus = if ($response.Content -match "OK") {"True"} else {"False"} } catch { $healthStatus = "False" } # 写入结果 $siteHealthResult += @{ SiteName = $site.Name RequestUrl = $requestUrl Healthy = $healthStatus } } # 导出为JSON文件 $siteHealthResult | ConvertTo-Json -Depth 3 | Out-File -FilePath "C:\health.json" -Encoding utf8
注意事项
- 若站点绑定的是域名,需要确保运行脚本的机器能正常解析该域名
- 可根据实际需求调整请求超时时间、响应匹配规则
- 导出的JSON默认使用UTF8编码,避免中文乱码
内容的提问来源于stack exchange,提问作者Jpmk
相关产品推荐
相关产品推荐

