使用powershell遍历在IIS中配置的所有绑定

Ful*_*yte 7 windows powershell iis-7

我正在寻找一种方法来完成我在IIS中配置的所有绑定设置.

我使用它来处理Powershell中的IIS:

Import-Module WebAdministration
Run Code Online (Sandbox Code Playgroud)

到目前为止,我能够获得我想要的主要信息:

$Websites = Get-ChildItem IIS:\Sites
Run Code Online (Sandbox Code Playgroud)

我的数组$网站已正确填写并使用以下命令...

$Websites[2]
Run Code Online (Sandbox Code Playgroud)

..我收到这个结果:

Name         ID   State    Physical Path       Bindings    
----         --   -----    -------------       --------------     
WebPage3      5            D:\Web\Page3        http  *:80:WebPage3  
                                               https *:443:WebPage3
Run Code Online (Sandbox Code Playgroud)

现在这是我遇到困难的部分:

我想检查绑定是否正确.为了做到这一点,我需要绑定.我试过了:

foreach ($site in $Websites)
{
    $site = $Websites[0]
    $site | select-string "http"
}
Run Code Online (Sandbox Code Playgroud)

调试该代码向我显示$ Site不包含我的预期:"Microsoft.IIs.PowerShell.Framework.ConfigurationElement".我目前不知道如何显式获取绑定信息,以达到类似这样的东西(在foreach循环内):

 if ($site.name -eq "WebPage3" -and $site.Port -eq "80") {
    #website is ok    
 } 
 else {
    #remove all current binding
    #add correct binding
 }
Run Code Online (Sandbox Code Playgroud)

谢谢您的帮助!


解:

Import-Module WebAdministration
$Websites = Get-ChildItem IIS:\Sites
foreach ($Site in $Websites) {

    $Binding = $Site.bindings
    [string]$BindingInfo = $Binding.Collection
    [string]$IP = $BindingInfo.SubString($BindingInfo.IndexOf(" "),$BindingInfo.IndexOf(":")-$BindingInfo.IndexOf(" "))         
    [string]$Port = $BindingInfo.SubString($BindingInfo.IndexOf(":")+1,$BindingInfo.LastIndexOf(":")-$BindingInfo.IndexOf(":")-1) 

    Write-Host "Binding info for" $Site.name " - IP:"$IP", Port:"$Port

    if ($Site.enabledProtocols -eq "http") {
        #DO CHECKS HERE     
    }
    elseif($site.enabledProtocols -eq "https") {
        #DO CHECKS HERE
    }
}
Run Code Online (Sandbox Code Playgroud)

ste*_*tej 7

我不知道你到底想要做什么,但我会尝试.我看到你引用的$Websites[2]webPage3.你可以这样做:

$site = $websites | Where-object { $_.Name -eq 'WebPage3' }
Run Code Online (Sandbox Code Playgroud)

然后,当你看到$site.Bindings,你会发现你需要Collection会员:

$site.bindings.Collection
Run Code Online (Sandbox Code Playgroud)

在我的机器上,这返回:

protocol                       bindingInformation
--------                       ------------------
http                           *:80:
net.tcp                        808:*
net.pipe                       *
net.msmq                       localhost
msmq.formatname                localhost
https                          *:443:
Run Code Online (Sandbox Code Playgroud)

然后测试可能如下所示:

$is80 = [bool]($site.bindings.Collection | ? { $_.bindingInformation -eq '*:80:' })
if ($is80) {
    #website is ok    
} else {
    #remove all current binding
    #add correct binding
 }
Run Code Online (Sandbox Code Playgroud)

我发送了内容Collection到管道和filtere只有属性bindingInformation等于所需值的对象(更改它).然后我把它投到了[bool].$true如果有所需项目,$false则返回,否则返回.