Skip to content

Instantly share code, notes, and snippets.

@simplyadrian
Created May 14, 2015 14:54
Show Gist options
  • Save simplyadrian/089309d350aefae98701 to your computer and use it in GitHub Desktop.
Save simplyadrian/089309d350aefae98701 to your computer and use it in GitHub Desktop.
Add port bindings to an IIS website.
# Powershell 2.0
if($env:RS_REBOOT){exit 0}
# Stop and fail script when a command fails.
$errorActionPreference = "Stop"
# load library functions
$rsLibDstDirPath = "$env:rs_sandbox_home\RightScript\lib"
. "$rsLibDstDirPath\tools\PsOutput.ps1"
. "$rsLibDstDirPath\tools\ResolveError.ps1"
try
{
$siteName = $env:WEB_SITE_NAME
$iis = [ADSI]"IIS://localhost/W3SVC"
$iis_site = $iis.psbase.children | where { $_.keyType -eq "IISWebServer" -AND $_.ServerComment -eq $siteName }
if($iis_site -eq $null)
{
throw "Site $siteName is not found. Please check the name and try again"
}
$iis_sites = $iis.psbase.children | where { $_.keyType -eq "IISWebServer"}
$new_port = ":$($env:APPLICATION_LISTENER_PORT):"
foreach ($iis_record in $iis_sites)
{
if (($($iis_record.Properties["ServerBindings"]) -eq $new_port) -and ($($iis_record.ServerComment) -ne $siteName))
{
throw "Port you are trying to use is already used for site $($iis_record.ServerComment)"
exit 0
}
if (($($iis_record.Properties["ServerBindings"]) -eq $new_port) -and ($($iis_record.ServerComment) -eq $siteName))
{
Write-Host "Port is already assigned to site $($iis_record.ServerComment)"
exit 0
}
}
[System.DirectoryServices.PropertyValueCollection]$serverBindings = $iis_site.Properties["ServerBindings"]
write-host "Setting port property to $new_port"
$serverBindings.Clear()
$serverBindings.Add($new_port) | Out-Null
$newlist=@(1)
$serverBindings.CopyTo($newlist,0)
$iis_site.Properties["ServerBindings"].Value = $newlist
$iis_site.CommitChanges()
$iis_site.Close()
$iis_site.Dispose()
}
catch
{
ResolveError
exit 1
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment