Skip to content

Instantly share code, notes, and snippets.

@Saanch
Last active December 15, 2017 00:21
Show Gist options
  • Save Saanch/57bc9d049c5b6875ef9b31608008b9ec to your computer and use it in GitHub Desktop.
Save Saanch/57bc9d049c5b6875ef9b31608008b9ec to your computer and use it in GitHub Desktop.
Configure IIS Website via Powershell script
Param (
[Parameter(Mandatory=$true)]
[string]$webSiteName,
[Parameter(Mandatory=$true)]
[string]$webSitePhysicalPath,
[Parameter(Mandatory=$true)]
[string]$webSiteAppPool,
[Parameter(Mandatory=$true)]
[string]$webSiteProtocol,
[Parameter(Mandatory=$true)]
[string]$webSitePort,
[Parameter(Mandatory=$true)]
[string]$webSiteSSLCertName
)
Configure-WebSite `
-webSiteName $webSiteName `
-webSitePhysicalPath $webSitePhysicalPath `
-webSiteAppPool $webSiteAppPool `
-webSiteProtocol $webSiteProtocol `
-webSitePort $webSitePort `
-webSiteSSLCertName $webSiteSSLCertName
Function Configure-WebSite(
$webSiteName,
$webSitePhysicalPath,
$webSiteAppPool,
$webSiteProtocol,
$webSitePort,
$webSiteSSLCertName
)
{
Import-Module WebAdministration
if ([string]::IsNullOrWhiteSpace($webSiteName)) {
throw "Missing webSiteName"
}
if (([string]::IsNullOrWhiteSpace($webSitePhysicalPath))) {
throw "Invalid webSitePhysicalPath"
}
if ([string]::IsNullOrWhiteSpace($webSiteAppPool)) {
throw "Missing webSiteAppPool"
}
if ([string]::IsNullOrWhiteSpace($webSiteProtocol)) {
throw "Missing webSiteProtocol"
}
if ([string]::IsNullOrWhiteSpace($webSitePort)) {
throw "Missing webSitePort"
}
$appPool = get-item iis:\apppools\$webSiteAppPool -ErrorAction SilentlyContinue
if(!$appPool)
{
$appPool = New-Item ("IIS:\AppPools\" + $webSiteAppPool)
}
#NetworkService\
$appPool.processmodel.identityType = 2
$appPool.processmodel.loadUserProfile = $true
$appPool | set-item
$site = Get-Website -Name $webSiteName
if($site)
{
Remove-Website `
-Name $webSiteName `
-EA SilentlyContinue
}
New-Website -Name $webSiteName -PhysicalPath $webSitePhysicalPath
Set-ItemProperty IIS:\Sites\$webSiteName -Name physicalPath -Value $webSitePhysicalPath
Set-ItemProperty IIS:\Sites\$webSiteName -Name applicationPool -Value $webSiteAppPool
Set-ItemProperty IIS:\Sites\$webSiteName -Name bindings -Value (@{protocol="$webSiteProtocol";bindingInformation="*:" + $webSitePort + ":"})
if ($webSiteProtocol -eq "https" -and $webSiteSSLCertName)
{
Push-Location IIS:\SslBindings
try {
$thumb = (Get-ChildItem cert:\LocalMachine\My | where-object { $_.Subject -like "CN=$webSiteSSLCertName" } | Select-Object -First 1).Thumbprint
Remove-Item 0.0.0.0!$webSitePort -ErrorAction SilentlyContinue
Get-Item cert:\LocalMachine\My\$thumb | New-Item 0.0.0.0!$webSitePort
} catch [Exception] {
$_ | fl * -Force
throw
}
Pop-Location
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment