Skip to content

Instantly share code, notes, and snippets.

@1k-off
Created April 27, 2022 10:48
Show Gist options
  • Save 1k-off/27e4299b68258ffa3c0ef616a2dc1bab to your computer and use it in GitHub Desktop.
Save 1k-off/27e4299b68258ffa3c0ef616a2dc1bab to your computer and use it in GitHub Desktop.
Migrate IIS websites with their bindings and configurations
param (
[Parameter(ParameterSetName="Task", Mandatory)]
[string]$Task
)
Import-Module WebAdministration
function ExportConfigurations {
param (
$WebsiteList
)
Write-Host "Exporting websites configs..."
Foreach ($w in $WebsiteList)
{
Get-Website -Name "$w" | ConvertTo-Json | Out-File "$ConfigBackup\$w.json"
}
}
function ImportConfigurations {
param (
$CongigPath
)
Write-Host "Importing websites configs..."
$files = Get-ChildItem $CongigPath -Recurse
Foreach ($f in $files)
{
$website = Get-Content -Raw -LiteralPath $CongigPath\$f | ConvertFrom-Json
New-Item -ItemType directory -Path $website.PhysicalPath -Force
New-WebAppPool -Name $website.Name
New-Website -Name $website.Name -Port 80 -HostHeader $website.Name -ApplicationPool $website.Name -PhysicalPath $website.PhysicalPath
Set-ItemProperty -Path IIS:\AppPools\$website.Name -Name "processModel.loadUserProfile" -Value "True"
Foreach ($b in $website.Bindings.Collection)
{
$port = $b.bindingInformation | %{ $_.Split(':')[1] }
$domain = $b.bindingInformation| %{ $_.Split(':')[2] }
$proto = $b.protocol
Write-Host "Importing ${proto}:${domain}"
$certHash = $b.certificateHash
$certStore = $b.certificateStoreName
$sslFlags = $b.sslFlags
$cert = (Get-ChildItem cert:\LocalMachine\My | where-object {$_.Thumbprint -match "$certHash"})
if ($domain -ne $website.Name) {
New-WebBinding -Name $website.Name -Protocol $proto -Port $port -HostHeader $domain -SslFlags $sslFlags
if ($proto -eq "https") {
(Get-WebBinding -Name $website.Name -Port 443 -Protocol "https" -HostHeader $domain).AddSslCertificate($cert.Thumbprint, "my")
}
}
}
}
}
$WorkingDirectory = "$PSScriptRoot"
$ConfigBackup = "$WorkingDirectory\IIS\Websites\Configuration"
[string[]]$Websites = Get-Content -Path "$WorkingDirectory\sitelist.txt"
if ( -not (Test-Path -LiteralPath "$ConfigBackup")) {
New-Item "$ConfigBackup" -ItemType Directory
}
switch ($Task)
{
"export" {ExportConfigurations -WebsiteList $Websites}
"import" {ImportConfigurations -CongigPath $ConfigBackup}
Default {Write-Host "Incorrect task value. Task may be `"import`" or `"export`""}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment