-
Notifications
You must be signed in to change notification settings - Fork 0
/
iis-website-create.ps1
232 lines (186 loc) · 8.75 KB
/
iis-website-create.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
## Creates a new IIS website together with a single HTTP binding.
## --------------------------------------------------------------------------------------
## Input
## --------------------------------------------------------------------------------------
param(
[Parameter(Mandatory=$True)][string]$applicationPoolName,
[Parameter(Mandatory=$True)][string]$bindingPort,
[Parameter(Mandatory=$True)][string]$bindingHost,
[Parameter(Mandatory=$True)][string]$webRoot
)
#Settings which do not need to be changed for this project
$webSiteName = $applicationPoolName #will be identical to pool name
$bindingProtocol = "http"
$bindingIpAddress = "*"
$bindingSslThumbprint = "" #project will not use SSL
$iisAuthentication = "Anonymous" #The authentication mode to use for the new website (can be Anonymous, Basic or Windows)
$webSiteStart = "true" #false if you don't want the website started after it is created
$anonymousAuthentication = "Anonymous"
$basicAuthentication = "Basic"
$windowsAuthentication = "Windows"
## --------------------------------------------------------------------------------------
## Helpers
## --------------------------------------------------------------------------------------
# Helper for validating input parameters
function Validate-Parameter($foo, [string[]]$validInput, $parameterName) {
Write-Host "${parameterName}: ${foo}"
if (! $foo) {
throw "$parameterName cannot be empty, please specify a value"
}
if ($validInput) {
@($foo) | % {
if ($validInput -notcontains $_) {
throw "'$_' is not a valid input for '$parameterName'"
}
}
}
}
# Helper to run a block with a retry if things go wrong
$maxFailures = 5
$sleepBetweenFailures = Get-Random -minimum 1 -maximum 4
function Execute-WithRetry([ScriptBlock] $command) {
$attemptCount = 0
$operationIncomplete = $true
while ($operationIncomplete -and $attemptCount -lt $maxFailures) {
$attemptCount = ($attemptCount + 1)
if ($attemptCount -ge 2) {
Write-Output "Waiting for $sleepBetweenFailures seconds before retrying..."
Start-Sleep -s $sleepBetweenFailures
Write-Output "Retrying..."
}
try {
& $command
$operationIncomplete = $false
} catch [System.Exception] {
if ($attemptCount -lt ($maxFailures)) {
Write-Output ("Attempt $attemptCount of $maxFailures failed: " + $_.Exception.Message)
}
else {
throw "Failed to execute command"
}
}
}
}
## --------------------------------------------------------------------------------------
## Validate Input
## --------------------------------------------------------------------------------------
Write-Output "Validating paramters..."
Validate-Parameter $webSiteName -parameterName "Web Site Name"
Validate-Parameter $applicationPoolName -parameterName "Application Pool Name"
Validate-Parameter $bindingProtocol -validInput @("HTTP", "HTTPS") -parameterName "Protocol"
Validate-Parameter $bindingPort -parameterName "Port"
if($bindingProtocol.ToLower() -eq "https") {
Validate-Parameter $bindingSslThumbprint -parameterName "SSL Thumbprint"
}
$enabledIisAuthenticationOptions = $iisAuthentication -split '\\s*[,;]\\s*'
Validate-Parameter $enabledIisAuthenticationOptions -validInput @($anonymousAuthentication, $basicAuthentication, $windowsAuthentication) -parameterName "IIS Authentication"
$enableAnonymous = $enabledIisAuthenticationOptions -contains $anonymousAuthentication
$enableBasic = $enabledIisAuthenticationOptions -contains $basicAuthentication
$enableWindows = $enabledIisAuthenticationOptions -contains $windowsAuthentication
## --------------------------------------------------------------------------------------
## Configuration
## --------------------------------------------------------------------------------------
if (! $webRoot) {
$webRoot = (Get-ItemProperty 'HKLM:\\SOFTWARE\\Microsoft\\InetStp' -name PathWWWRoot).PathWWWRoot
}
$webRoot = (resolve-path $webRoot).ProviderPath
Validate-Parameter $webRoot -parameterName "Relative Home Directory"
$bindingInformation = "${bindingIpAddress}:${bindingPort}:${bindingHost}"
Add-PSSnapin WebAdministration -ErrorAction SilentlyContinue
Import-Module WebAdministration -ErrorAction SilentlyContinue
$wsBindings = new-object System.Collections.ArrayList
$wsBindings.Add(@{ protocol=$bindingProtocol;bindingInformation=$bindingInformation }) | Out-Null
if (! [string]::IsNullOrEmpty($bindingSslThumbprint)) {
$wsBindings.Add(@{ thumbprint=$bindingSslThumbprint }) | Out-Null
$sslCertificateThumbprint = $bindingSslThumbprint.Trim()
Write-Output "Finding SSL certificate with thumbprint $sslCertificateThumbprint"
$certificate = Get-ChildItem Cert:\\LocalMachine -Recurse | Where-Object { $_.Thumbprint -eq $sslCertificateThumbprint -and $_.HasPrivateKey -eq $true } | Select-Object -first 1
if (! $certificate)
{
throw "Could not find certificate under Cert:\\LocalMachine with thumbprint $sslCertificateThumbprint. Make sure that the certificate is installed to the Local Machine context and that the private key is available."
}
Write-Output ("Found certificate: " + $certificate.Subject)
if ((! $bindingIpAddress) -or ($bindingIpAddress -eq '*')) {
$bindingIpAddress = "0.0.0.0"
}
$port = $bindingPort
$sslBindingsPath = ("IIS:\\SslBindings" + $bindingIpAddress + "!" + $port)
Execute-WithRetry {
$sslBinding = get-item $sslBindingsPath -ErrorAction SilentlyContinue
if (! $sslBinding) {
New-Item $sslBindingsPath -Value $certificate | Out-Null
} else {
Set-Item $sslBindingsPath -Value $certificate | Out-Null
}
}
}
## --------------------------------------------------------------------------------------
## Run
## --------------------------------------------------------------------------------------
pushd IIS:\\
$appPoolPath = ("IIS:\\AppPools\" + $applicationPoolName)
Execute-WithRetry {
Write-Output "Finding application pool $applicationPoolName"
$pool = Get-Item $appPoolPath -ErrorAction SilentlyContinue
if (!$pool) {
throw "Application pool $applicationPoolName does not exist"
}
}
$sitePath = ("IIS:\\Sites\" + $webSiteName)
Write-Output $sitePath
$site = Get-Item $sitePath -ErrorAction SilentlyContinue
if (!$site) {
Write-Output "Creating web site $webSiteName"
$id = (dir iis:\\sites | foreach {$_.id} | sort -Descending | select -first 1) + 1
new-item $sitePath -bindings ($wsBindings[0]) -id $id -physicalPath $webRoot -confirm:$false
} else {
write-host "Web site $webSiteName already exists"
}
$cmd = {
Write-Output "Assigning website to application pool: $applicationPoolName"
Set-ItemProperty $sitePath -name applicationPool -value $applicationPoolName
}
Execute-WithRetry -Command $cmd
Execute-WithRetry {
Write-Output "Setting home directory: $webRoot"
Set-ItemProperty $sitePath -name physicalPath -value "$webRoot"
}
try {
Execute-WithRetry {
Write-Output "Anonymous authentication enabled: $enableAnonymous"
Set-WebConfigurationProperty -filter /system.webServer/security/authentication/anonymousAuthentication -name enabled -value "$enableAnonymous" -location $WebSiteName -PSPath "IIS:"
}
Execute-WithRetry {
Write-Output "Basic authentication enabled: $enableBasic"
Set-WebConfigurationProperty -filter /system.webServer/security/authentication/basicAuthentication -name enabled -value "$enableBasic" -location $WebSiteName -PSPath "IIS:"
}
Execute-WithRetry {
Write-Output "Windows authentication enabled: $enableWindows"
Set-WebConfigurationProperty -filter /system.webServer/security/authentication/windowsAuthentication -name enabled -value "$enableWindows" -location $WebSiteName -PSPath "IIS:"
}
} catch [System.Exception] {
Write-Output "Authentication options could not be set. This can happen when there is a problem with your application's web.config. For example, you might be using a section that requires an extension that is not installed on this web server (such as URL Rewriting). It can also happen when you have selected an authentication option and the appropriate IIS module is not installed (for example, for Windows authentication, you need to enable the Windows Authentication module in IIS/Windows first)"
throw
}
# It can take a while for the App Pool to come to life
Start-Sleep -s 1
Execute-WithRetry {
$state = Get-WebAppPoolState $applicationPoolName
if ($state.Value -eq "Stopped") {
Write-Output "Application pool is stopped. Attempting to start..."
Start-WebAppPool $applicationPoolName
}
}
if($webSiteStart -eq $true) {
Execute-WithRetry {
$state = Get-WebsiteState $webSiteName
if ($state.Value -eq "Stopped") {
Write-Output "Web site is stopped. Attempting to start..."
Start-Website $webSiteName
}
}
} else {
write-host "Not starting Web site $webSiteName"
}
popd
Write-Output "IIS configuration complete"