如何使用PowerShell从WebBinding对象中获取对应的网站名称
实现方案
方案1:直接读取内置Name属性(最简实现)
Get-WebBinding返回的WebBinding对象原生携带所属站点的名称属性,属性名为Name,可直接调用获取:
# 示例:遍历所有HTTPS绑定,筛选缺失SSL配置的条目并输出对应站点信息 Get-WebBinding -Protocol https | Where-Object { # 此处替换为你已有的SSL绑定不匹配判断逻辑 $_.certificateHash -eq '' -and $_.sslFlags -notin 2,3 # sslFlags=2/3对应CCS证书绑定 } | ForEach-Object { [PSCustomObject]@{ 所属站点名称 = $_.Name 绑定信息 = $_.bindingInformation 证书哈希 = $_.certificateHash SSL配置标记 = $_.sslFlags } }
方案2:多属性兜底兼容特殊场景
如果遇到共享IIS配置场景下Name属性为空的异常情况,可以通过解析ItemXPath或PSParentPath属性提取站点名,兼容所有场景:
function Get-SiteNameByBinding { param( [Parameter(Mandatory=$true)] [Microsoft.IIs.PowerShell.Framework.ConfigurationElement]$WebBinding ) # 优先读取原生Name属性 if (-not [string]::IsNullOrWhiteSpace($WebBinding.Name)) { return $WebBinding.Name } # 第一层兜底:解析ItemXPath if ($WebBinding.ItemXPath -match '/site\[@name=''([^'']+)''\]') { return $matches[1] } # 第二层兜底:解析PSParentPath if ($WebBinding.PSParentPath -match '\\sites\\([^\\]+)') { return $matches[1] } return "未识别站点" } # 调用示例 $invalidBindings = @() # 替换为你已经生成的未匹配SSL绑定的列表 foreach ($bind in $invalidBindings) { $siteName = Get-SiteNameByBinding -WebBinding $bind Write-Host "异常绑定所属站点:$siteName,绑定地址:$($bind.bindingInformation)" }
注:SSL标记枚举说明:0=本地普通证书、1=本地SNI证书、2=CCS非SNI证书、3=CCS SNI证书,可根据你的实际校验规则调整判断条件。
内容的提问来源于stack exchange,提问作者Raymond Brink
相关产品推荐
相关产品推荐

