IT

PowerShell의 모든 사이트 및 바인딩 표시

itgroup 2023. 8. 11. 21:42
반응형

PowerShell의 모든 사이트 및 바인딩 표시

저는 모든 사이트를 문서화하고 있으며 IIS에서 사이트와 관련된 바인딩을 참조하십시오.IIS에서 수동으로 입력하는 것보다 PowerShell 스크립트를 통해 이 목록을 쉽게 가져올 수 있는 방법이 있습니까?

출력은 다음과 같습니다.

Site                          Bindings
TestSite                     www.hello.com
                             www.test.com
JonDoeSite                   www.johndoe.site

사용해 보십시오.

Import-Module Webadministration
Get-ChildItem -Path IIS:\Sites

다음과 같은 것을 반환해야 합니다.

Name             ID   State      Physical Path                  Bindings
----             --   -----      -------------                  --------
ChristophersWeb 22   Started    C:\temp             http *:8080:ChristophersWebsite.ChDom.com

여기서 결과를 세분화할 수 있지만 주의해야 합니다.select 문에 파이프를 연결해도 필요한 것을 얻을 수 없습니다.당신의 요구 사항을 기반으로 사용자 지정 개체 또는 해시 테이블을 만들 것입니다.

원하는 형식을 얻으려면 다음과 같은 방법을 사용하십시오.

Get-WebBinding | % {
    $name = $_.ItemXPath -replace '(?:.*?)name=''([^'']*)(?:.*)', '$1'
    New-Object psobject -Property @{
        Name = $name
        Binding = $_.bindinginformation.Split(":")[-1]
    }
} | Group-Object -Property Name | 
Format-Table Name, @{n="Bindings";e={$_.Group.Binding -join "`n"}} -Wrap

모든 사이트를 나열하려는 경우(즉, 바인딩을 찾는 경우)

작업 디렉토리를 "C:"로 변경합니다.\Windows\system32\inetsrv"

cd c:\Windows\system32\inetsrv

다음으로 "appcmd list sites"(복수)를 실행하고 파일로 출력합니다(예: c:\).IISSiteBindings.txt

appcmd 사이트 목록 > c:\IISSiteBindings.txt

이제 명령 프롬프트에서 메모장으로 엽니다.

메모장 c:\IISSiteBindings.txt

내가 본 가장 쉬운 방법은:

Foreach ($Site in get-website) { Foreach ($Bind in $Site.bindings.collection) {[pscustomobject]@{name=$Site.name;Protocol=$Bind.Protocol;Bindings=$Bind.BindingInformation}}}

사용해 보세요.

function DisplayLocalSites
{

try{

Set-ExecutionPolicy unrestricted

$list = @()
foreach ($webapp in get-childitem IIS:\Sites\)
{
    $name = "IIS:\Sites\" + $webapp.name
    $item = @{}

$item.WebAppName = $webapp.name

foreach($Bind in $webapp.Bindings.collection)
{
    $item.SiteUrl = $Bind.Protocol +'://'+         $Bind.BindingInformation.Split(":")[-1]
}


$obj = New-Object PSObject -Property $item
$list += $obj
}

$list | Format-Table -a -Property "WebAppName","SiteUrl"

$list | Out-File -filepath C:\websites.txt

Set-ExecutionPolicy restricted

}
catch
{
$ExceptionMessage = "Error in Line: " + $_.Exception.Line + ". " +     $_.Exception.GetType().FullName + ": " + $_.Exception.Message + " Stacktrace: "    + $_.Exception.StackTrace
$ExceptionMessage
}
}
function Get-ADDWebBindings {
param([string]$Name="*",[switch]$http,[switch]$https)
    try {
    if (-not (Get-Module WebAdministration)) { Import-Module WebAdministration }
    Get-WebBinding | ForEach-Object { $_.ItemXPath -replace '(?:.*?)name=''([^'']*)(?:.*)', '$1' } | Sort | Get-Unique | Where-Object {$_ -like $Name} | ForEach-Object {
        $n=$_
        Get-WebBinding | Where-Object { ($_.ItemXPath -replace '(?:.*?)name=''([^'']*)(?:.*)', '$1') -like $n } | ForEach-Object {
            if ($http -or $https) {
                if ( ($http -and ($_.protocol -like "http")) -or ($https -and ($_.protocol -like "https")) ) {
                    New-Object psobject -Property @{Name = $n;Protocol=$_.protocol;Binding = $_.bindinginformation}
                }
            } else {
                New-Object psobject -Property @{Name = $n;Protocol=$_.protocol;Binding = $_.bindinginformation}
            }
        }
    }
    }
    catch {
       $false
    }
}

바인딩이 많은 사이트를 새 서버로 마이그레이션해야 했기 때문에 이 페이지를 찾았습니다.나는 여기에 있는 코드 중 일부를 사용하여 아래의 powershell 스크립트를 생성하여 새 서버에 바인딩을 추가했습니다.다른 사용자에게 유용한 경우 공유:

Import-Module WebAdministration
$Websites = Get-ChildItem IIS:\Sites
$site = $Websites | Where-object { $_.Name -eq 'site-name-in-iis-here' }

$Binding = $Site.bindings
[string]$BindingInfo = $Binding.Collection
[string[]]$Bindings = $BindingInfo.Split(" ")
$i = 0
$header = ""
Do{
    [string[]]$Bindings2 = $Bindings[($i+1)].Split(":")

    Write-Output ("New-WebBinding -Name `"site-name-in-iis-here`" -IPAddress " + $Bindings2[0] + " -Port " + $Bindings2[1] + " -HostHeader `"" + $Bindings2[2] + "`"")

    $i=$i+2
} while ($i -lt ($bindings.count))

다음과 같은 레코드를 생성합니다.

New-WebBinding -Name "site-name-in-iis-here" -IPAddress "*" -Port 80 -HostHeader www.aaa.com

IIS 10.0+(2017+) 업데이트

다음과 같은 cmdlet과 함께 최신 모듈을 사용할 수 있습니다.

PS> Import-Module IISAdministration
PS> Get-IISSite

Name             ID   State      Physical Path                  Bindings
----             --   -----      -------------                  --------
Default Web Site 1    Started    %SystemDrive%\inetpub\wwwroot  http *:80: 
PattiFul         2    Stopped    C:\inetpub\PattiFul            http *:8080: 
                                                                http *:8033: 
FTPSite          3               C:\inetpub\ftproot             ftp *:21: 
DavidChe         4    Started    c:\                            http *:8088: 
MyNewSite        6555 Started    C:\inetpub\wwwroot             http *:8099: 
                                                                http *:8022:

IIS 인스턴스에서 실행 중인 모든 웹 사이트에 대한 링크가 포함된 웹 페이지를 생성하기 위해 이 질문을 발견했습니다.저는 알렉산더 섀프킨의 답변을 사용하여 많은 링크를 생성하기 위해 다음을 생각해냈습니다.

$hostname = "localhost"

Foreach ($Site in get-website) {
    Foreach ($Bind in $Site.bindings.collection) {
        $data = [PSCustomObject]@{
            name=$Site.name;
            Protocol=$Bind.Protocol;
            Bindings=$Bind.BindingInformation
        }
        $data.Bindings = $data.Bindings -replace '(:$)', ''
        $html = "<a href=""" + $data.Protocol + "://" + $data.Bindings + """>" + $data.name + "</a>"
        $html.Replace("*", $hostname);
    }
}

그런 다음 급하게 작성된 HTML에 결과를 붙여넣습니다.

<html>
<style>
    a { display: block; }
</style>
{paste PowerShell results here}
</body>
</html>

언급URL : https://stackoverflow.com/questions/15528492/display-all-sites-and-bindings-in-powershell

반응형