-
Notifications
You must be signed in to change notification settings - Fork 35
/
MigrateIISWebsiteToElasticBeanstalk.ps1
3040 lines (2625 loc) · 107 KB
/
MigrateIISWebsiteToElasticBeanstalk.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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License").
# You may not use this file except in compliance with the License.
# A copy of the License is located at
#
# http://aws.amazon.com/apache2.0
#
# or in the "license" file accompanying this file. This file is distributed
# on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
# express or implied. See the License for the specific language governing
# permissions and limitations under the License.
<#------------------------------------------------------------------------------------------------------------------------------#
SYNOPSIS
Microsoft .NET application modernization utility that migrates IIS websites from Windows servers to AWS Elastic Beanstalk.
DEPENDENCIES
MS PowerShell version 3.0 or above.
#------------------------------------------------------------------------------------------------------------------------------#>
param (
[switch]$NonInteractiveMode = $False,
[string]$ProfileLocation,
[string]$ProfileName,
[string]$Region,
[string]$ApplicationIndex,
[string]$ConnectionStringIndex,
[string]$NewConnectionString,
[string]$WindowsPlatformIndex,
[string]$InstanceType,
[string]$ApplicationName,
[string]$EnvironmentType,
[switch]$ReportOnly = $False
)
if ($NonInteractiveMode){
Write-Host "NonInteractiveMode: $NonInteractiveMode, Location: $ProfileLocation, Profile: $ProfileName, Region: $Region, ApplicationIndex: $ApplicationIndex, ConnectionStringIndex: $ConnectionStringIndex, NewConnectionString: $NewConnectionString, Platform Index: $WindowsPlatformIndex, InstanceType: $InstanceType, App Name: $ApplicationName, Environment Type: $EnvironmentType"
}
$Global:mfarg_awsprofilename = $ProfileName
$Global:mfarg_awsprofilelocation = $ProfileLocation
$Global:mfarg_region = $Region
$Global:mfarg_websitenumstr = $ApplicationIndex
$Global:mfarg_glb_ebAppName = $ApplicationName
$Global:mfarg_userInputWindowsStringNum = $WindowsPlatformIndex
$Global:mfarg_instanceType = $InstanceType
$Global:mfarg_userInputConnectionString = $NewConnectionString
$Global:mfarg_userInputConnectionStringNum = $ConnectionStringIndex
$Global:mfarg_userInputEnvironmentTypeNum = $EnvironmentType
$Global:mfarg_userconsent = $False
$Global:mfarg_userinputI = "NonInteractiveMode"
$Global:mfarg_userinputY = "Y"
$Global:mfarg_userinputK = "K"
#Requires -RunAsAdministrator
$ErrorActionPreference = "Stop"
function Global:Test-PowerShellSessionRole {
<#
.SYNOPSIS
This function checks if the current session is of the specified windows built-in role
.INPUTS
Windows built-in role
.OUTPUTS
Boolean - if the input role matches with session role or not
.EXAMPLE
Test-PowerShellSessionRole -Role Administrator
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[System.Security.Principal.WindowsBuiltInRole]
$Role
)
$currentSessionIdentity = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$currentSessionPrincipal = New-Object System.Security.Principal.WindowsPrincipal($currentSessionIdentity)
$currentSessionPrincipal.IsInRole($Role)
}
function Global:Get-WebsiteByName {
<#
.SYNOPSIS
Calls Get-Website with the name argument and returns the correct website - bugfix for MS
.INPUTS
Name of the website (website names are unique by default on a single server)
.OUTPUTS
ConfigurationElement object that represents the website
.EXAMPLE
Get-WebsiteByName NopCommerce380
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[String]
$Name
)
$website = Get-Website | where { $_.Name -eq $Name }
if ($website -eq $null) {
throw "ERROR: Cannot get website $Name"
}
$website
}
function Global:Get-WebDeployV3Exe {
<#
.SYNOPSIS
Returns the path of Web Deploy Version 3 executable
.INPUTS
None
.OUTPUTS
String - local path of the msDeploy.exe
#>
[CmdletBinding()]
param ()
$webDeployV3Key = "HKLM:\SOFTWARE\Microsoft\IIS Extensions\MSDeploy\3"
if (!(Test-Path $webDeployV3Key)) {
throw "ERROR: Cannot find Web Deploy v3"
}
$installPath = (Get-ItemProperty $webDeployV3Key -Name InstallPath | Select -ExpandProperty InstallPath)
if ($installPath -eq $null) {
throw "ERROR: Cannot find installation path of Web Deploy v3"
}
$installPath + "msdeploy.exe"
}
function Global:Verify-WebsiteExists {
<#
.SYNOPSIS
Verifies if the given website exists on the local machine
.INPUTS
Name of the website
.OUTPUTS
None - will throw exception when test fails
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[String]
$WebsiteName
)
$site = Get-Website | Where-Object { $_.name -eq $WebsiteName }
if (-Not $site) {
Throw "ERROR: Cannot find website $WebsiteName"
}
}
function Global:Verify-PathExists {
<#
.SYNOPSIS
Verifies if the given path exists
.INPUTS
A full physical path
.OUTPUTS
None - will throw exception when test fails
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[String]
$PathToTest
)
if (!(Test-Path -Path $PathToTest)) {
throw "ERROR: $PathToTest does not exist."
}
}
function Global:Verify-FolderExistsAndEmpty {
<#
.SYNOPSIS
Tests if the given path:
1. Exists
2. Is a folder
3. Is empty
.INPUTS
Full physical path of the folder
.OUTPUTS
None - will throw exception when test fails
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[String]
$PathToTest
)
Verify-PathExists $PathToTest
if (!((Get-Item $PathToTest) -is [System.IO.DirectoryInfo])) {
throw "ERROR: Path $PathToTest is not a folder."
}
$dirInfo = Get-ChildItem $PathToTest | Measure-Object
if ($dirInfo.count -ne 0) {
throw "ERROR: Folder $PathToTest is not empty."
}
}
function Global:Get-ZippedFolder {
<#
.SYNOPSIS
This function zips a folder, generating the result file into the output folder
.INPUTS
1. Full physical path of the folder to be zipped
2. Full physical path of the output folder
3. Name of the result file
.OUTPUTS
Full physical path of the result zip file
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[String]
$SourceFolderPath,
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[String]
$OutputFolderPath,
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[String]
$ZipFileName
)
Verify-PathExists $SourceFolderPath
Verify-PathExists $OutputFolderPath
$resultFilePath = Join-Path $OutputFolderPath $ZipFileName
$compressionLevel = [System.IO.Compression.CompressionLevel]::Optimal
[System.IO.Compression.ZipFile]::CreateFromDirectory($SourceFolderPath, $resultFilePath, $compressionLevel, $false)
$resultFilePath
}
function Global:Unzip-Folder {
<#
.SYNOPSIS
This function unzips a zip file and releases the contents into the output folder
.INPUTS
1. Full physical path of the zip file
2. Full physical path of the output folder - it must be an empty and existing folder
.OUTPUTS
None
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[String]
$ZipFilePath,
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[String]
$OutputFolderPath
)
Verify-PathExists $ZipFilePath
Verify-FolderExistsAndEmpty $OutputFolderPath
[System.IO.Compression.ZipFile]::ExtractToDirectory($ZipFilePath, $OutputFolderPath)
}
function Global:New-Folder {
<#
.SYNOPSIS
Creates a new folder item and logs the event to (global) $ItemCreationLogFile
.INPUTS
1. Path to the parent folder
2. Name of the new folder
3. Whether to return the full physical path of the new folder or not
.OUTPUTS
Full physical path of the new folder (on demand)
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[String]
$ParentPath,
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[String]
$FolderName,
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[Boolean]
$ReturnFolderPath
)
$folder = New-Item -Path $ParentPath -Name $FolderName -ItemType Directory -Force
$folder | Out-File -append $ItemCreationLogFile
if ($ReturnFolderPath) {
$folder.ToString()
}
}
function Global:New-File {
<#
.SYNOPSIS
Creates a new file item and logs the event to (global) $ItemCreationLogFile
.INPUTS
1. Path to the parent folder
2. Name of the new file
3. Whether to return the full physical path of the new file or not
.OUTPUTS
Full physical path of the new file (on demand)
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[String]
$ParentPath,
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[String]
$FileName,
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[Boolean]
$ReturnFilePath
)
$file = New-Item -Path $ParentPath -Name $FileName -ItemType File -Force
$file | Out-File -append $ItemCreationLogFile
if ($ReturnFilePath) {
$file.ToString()
}
}
function Global:Delete-Item {
<#
.SYNOPSIS
Deletes a file or folder and all of its contents (use at clean-up time)
.INPUTS
Full physical path of the file or folder
.OUTPUTS
None
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[String]
$PathToDelete
)
Remove-Item $PathToDelete -Recurse -ErrorAction Ignore
}
function Global:Get-RandomPassword {
([char[]]([char]97..[char]122) + [char[]]([char]65..[char]90) + 0..9 | sort {Get-Random})[0..24] -join ''
}
function Global:Exit-WithError {
exit 1
}
function Global:Exit-WithoutError {
exit 0
}
# Types of log message
$Global:InfoMsg = "Info"
$Global:DebugMsg = "Debug"
$Global:ErrorMsg = "Error"
$Global:FatalMsg = "FATAL"
# use this to exclude sensitive data from logs
$Global:ConsoleOnlyMsg = "ConsoleOnly"
# AWS EB Migration Support
$Global:SupportTeamAWSRegion = ""
function Global:Write-Log {
<#
.NOTES
DO NOT USE THIS FUNCTION DIRECTLY - use New-Message
except when the log files are not initialized yet
.SYNOPSIS
This function writes a log line into specified log file
.INPUTS
1. Full physical path of the log file. It must be initialized before this function call
2. Type of the message ($InfoMsg, $DebugMsg, $ErrorMsg, or $FatalMsg)
3. The log message (a string)
.OUTPUTS
None
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[String]
$LogFilePath,
[Parameter(Mandatory = $true)]
[ValidateSet("Info", "Debug", "Error", "FATAL")]
[String]
$MessageType,
[Parameter(Mandatory = $true)]
[String]
$LogMessage
)
Verify-PathExists $LogFilePath
$timeStampNow = [datetime]::Now.ToString('yyyy-MM-dd HH:mm:ss.fff')
$fullMessage = "$timeStampNow : $MessageType : $LogMessage"
Add-Content $LogFilePath -Value $fullMessage
}
function Global:Get-SessionObjectFilePath ($ID) {
$objectFileName = $ID + ".xml"
$sessionFolderPath = Join-Path $MigrationRunDirPath $SessionFolderName
Join-Path $sessionFolderPath $objectFileName
}
function Global:New-SessionFolder {
<#
.SYNOPSIS
This function needs to be invoked before any function in this file is called.
It creates a folder under the current migration run folder to contain session resumability files.
The name of the folder needs to be defined in the global scope as $SessionFolderName
.INPUTS
None
.OUTPUTS
None
.NOTES
Please only create the folder right before you write the first set of session data
Then you can use Test-SessionFolderExists to identify if a migration run is resumable
#>
Verify-PathExists $MigrationRunDirPath
$sessionFolderPath = Join-Path $MigrationRunDirPath $SessionFolderName
if (-Not (Test-Path $sessionFolderPath)) {
New-Folder $MigrationRunDirPath $SessionFolderName $False
}
}
function Global:Test-SessionFolderExists {
<#
.SYNOPSIS
Tests if the session folder exists for ANY migration run
.INPUTS
Migration run ID
.OUTPUTS
Boolean
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[String]
$MigrationRunID
)
$testMigrationRunDirPath = Join-Path $MigrationRunsDirPath $MigrationRunID
if (Test-Path $testMigrationRunDirPath) {
$testSessionFolderPath = Join-Path $testMigrationRunDirPath $sessionFolderName
Test-Path $testSessionFolderPath
return
}
$False
}
function Global:Save-SessionObject {
<#
.SYNOPSIS
This function serializes any PS object into a new or existing file under the session folder
.INPUTS
1. the PS object to serialize
2. NAME (not path - and without extension) of the file to store the data
.OUTPUTS
None
.EXAMPLE
Save-SessionObject $iisSitesConfigStage "iis_sites_config_stage"
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[PSObject]
$Object,
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[String]
$Name
)
$objectFilePath = Get-SessionObjectFilePath $Name
if (Test-Path $objectFilePath) {
Remove-Item $objectFilePath
}
$serializedString = [System.Management.Automation.PSSerializer]::Serialize($Object)
$serializedString | Out-File $objectFilePath
}
function Global:Restore-SessionObject {
<#
.SYNOPSIS
This function restores any previously saved PS object
.INPUTS
NAME (not path - and without extension) of the file that stores the data
.OUTPUTS
PS object
.EXAMPLE
$iisSitesConfigStage = Restore-sessionObject "iis_sites_config_stage"
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[String]
$Name
)
$objectFilePath = Get-SessionObjectFilePath $Name
if (-Not (Test-Path $objectFilePath)) {
throw "Resumption Failed. Cannot find session file $objectFilePath"
}
$serializedString = Get-Content $objectFilePath
[System.Management.Automation.PSSerializer]::Deserialize($serializedString)
}
<#
Global Variables Defined in Setup-Workspace:
$SessionFolderName
$MigrationRunsDirPath
Global Variables Defined in Setup-NewMigrationRun:
$CurrentMigrationRunPath
$LogFolderPath
$ItemCreationLogFile
$MigrationRunLogFile
$EnvironmentInfoLogFile
#>
function Global:Setup-Workspace {
<#
.SYNOPSIS
Call this function before anything else
.INPUTS
None
.OUTPUTS
None
#>
# Global & universal variables for all migration runs
$Global:SessionFolderName = "session"
$Global:MigrationRunsDirPath = Join-Path $runDirectory "runs"
# need to test role first otherwise log file/folder creation may fail
if (-Not (Test-PowerShellSessionRole -Role Administrator)) {
Write-Host "Error: Run the migration assistant as Administrator."
Exit-WithError
}
}
function Global:Setup-NewMigrationRun {
<#
.SYNOPSIS
Call this function to set up the workspace for a new migration run
.INPUTS
Migration run ID
.OUTPUTS
None
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[String]
$MigrationRunID
)
# Create the main runs folder if it doesn't exist
if (-Not (Test-Path $MigrationRunsDirPath)) {
New-Item -Path $MigrationRunsDirPath -Force -ItemType Directory | Out-Null
}
$Global:CurrentMigrationRunPath = Join-Path $MigrationRunsDirPath $MigrationRunId
$Global:LogFolderPath = Join-Path $CurrentMigrationRunPath "logs"
if (Test-Path -Path $CurrentMigrationRunPath) {
Write-Host "Error: $MigrationRunId already exists. Run the migration assistant again."
Exit-WithError
}
try {
$currentMigrationRunPathObj = New-Item -Path $CurrentMigrationRunPath -Force -ItemType Directory
$logFolderPathObj = New-Item -Path $LogFolderPath -Force -ItemType Directory
$itemCreationLogFileName = "item_creation.log"
$itemCreationLogFileObj = New-Item -Path $LogFolderPath -Name $itemCreationLogFileName -ItemType File
$Global:ItemCreationLogFile = $itemCreationLogFileObj.ToString()
$currentMigrationRunPathObj | Out-File -append $ItemCreationLogFile
$logFolderPathObj | Out-File -append $ItemCreationLogFile
$itemCreationLogFileObj | Out-File -append $ItemCreationLogFile
$migrationRunLogFileName = "migration_run.log"
$Global:MigrationRunLogFile = New-File $LogFolderPath $migrationRunLogFileName $True
# does not initiate this log file - Write-IISServerInfo will make the file
$Global:EnvironmentInfoLogFile = Join-Path $LogFolderPath "environment_info.log"
} catch {
Write-Host "Error: Can't create required items. Be sure you have write permission on the 'runs' folder."
Exit-WithError
}
}
function Global:Invoke-CommandsWithRetry {
<#
.SYNOPSIS
This function automatically repeats the input script block when an exception is thrown within retry # limit
Before repeating, the exception will be shown in the console as an error message
Also logs the exception message into the specified log file
If the max number of retry is reached, an exception will be thrown
.INPUTS
1. Number of max retries
1. Full physical path of the log file
2. The script block to execute
.OUTPUTS
None
.EXAMPLE
$Global:myGlobalVar = "27"
Invoke-CommandsWithRetry 3 $logFile {
$string = Get-UserInputString $logFile "Type anything other than 27"
if ($string -eq "27") {
throw "That's the only number that doesn't work!"
}
$Global:myGlobalVar = $string
}
Echo $myGlobalVar # console will print the string user typed in
.NOTES
1. if you declare any variable within the script block, it will not be accessible outside unless made global
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[Int]
$MaxRetryNumber,
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[String]
$LogFilePath,
[Parameter(Mandatory=$true)]
[ScriptBlock]$ScriptBlock
)
Begin {
$retryCount = -1
}
Process {
do {
$retryCount++
try {
$ScriptBlock.Invoke()
return
} catch {
$lastExceptionMessage = $error[0].Exception.Message
$innerExceptionMessage = $lastExceptionMessage.Replace("Exception calling `"Invoke`" with `"0`" argument(s): ", "")
New-Message $ErrorMsg $innerExceptionMessage $LogFilePath
New-Message $InfoMsg "Retrying command." $LogFilePath
}
} while ($retryCount -lt $MaxRetryNumber)
$logLine = "Max retry number exceeded for script block: " + $ScriptBlock.ToString()
New-Message $DebugMsg $logLine $LogFilePath
throw "Max retry number exceeded."
}
}
function Global:Get-UserFacingMessage ($Message) {
$messagePrefix = "[AWS Migration] "
if ($DisplayTimestampsInConsole) {
$timestampNow = [datetime]::Now.ToString('yyyy-MM-dd HH:mm')
$messagePrefix = "[$timestampNow] "
}
if ($Message) {
$messagePrefix + $Message
} else {
$messagePrefix
}
}
function Global:New-Message {
<#
.SYNOPSIS
This function generates a new message. Depending on the message type, it
1. displays this message to the user via the console (with timestamp, when $DisplayTimestampsInConsole is on)
2. stores the message as a new log line (with timestamp)
.INPUTS
1. Type of message ($InfoMsg, $DebugMsg, $ErrorMsg, or $FatalMsg)
a. $InfoMsg: the message will go to the user & log file
b. $DebugMsg: the message will only go to the log file
c. $ErrorMsg: the message will go to the user & log file. Additional information is added to user facing message
d. $FatalMsg: the message will go to the user & log file. Additional information is added to user facing message
2. The message itself (a string)
2. Full physical path of the log file. It must be initialized before this function call
.OUTPUTS
None
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[ValidateSet("Info", "Debug", "Error", "FATAL", "ConsoleOnly")]
[String]
$MessageType,
[Parameter(Mandatory = $true)]
[String]
$Message,
[Parameter(Mandatory = $true)]
[String]
$LogFilePath
)
if ($MessageType -ne "ConsoleOnly") {
Write-Log $LogFilePath $MessageType $Message
}
$userFacingMessage = $Message
if (($MessageType -eq "Error") -or ($MessageType -eq "FATAL")) {
$userFacingPrefix = "[$MessageType] "
$fullTimeStampNow = [datetime]::Now.ToString('yyyy-MM-dd HH:mm:ss.fff')
$userFacingSuffix = " (at $fullTimeStampNow)"
$userFacingMessage = $userFacingPrefix + $userFacingMessage + $userFacingSuffix
}
$color = "White"
switch ($MessageType) {
"Error" { $color = "Yellow"; break }
"FATAL" { $color = "Red"; break }
default { break }
}
if ($MessageType -ne "Debug") {
$messageToDisplay = Get-UserFacingMessage $userFacingMessage
Write-Host $messageToDisplay -ForegroundColor $color
}
}
function Global:Get-UserInputString {
<#
.SYNOPSIS
This function does the following things:
1. display an optional prompt message to the user (with timestamp, when $DisplayTimestampsInConsole is on)
2. collect and return the text input from the user as a string
3. add the user input to the specified log file
.INPUTS
1. full physical path to the log file
2. prompt message (optional) - please do not include ":"
.OUTPUTS
User input as a string
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[String]
$LogFilePath,
[Parameter(Mandatory = $false)]
[String]
$PromptMessage
)
if ($PromptMessage) {
$promptMessageLogLine = "UserInterface-Prompt : " + $PromptMessage
Write-Log $LogFilePath $InfoMsg $promptMessageLogLine
}
$userFacingPromptMessage = Get-UserFacingMessage $PromptMessage
$userInput = Read-Host -Prompt $userFacingPromptMessage
$userInputLogLine = "UserInterface-Input : " + $userInput
Write-Log $LogFilePath $InfoMsg $userInputLogLine
$userInput
}
function Global:Get-SensitiveUserInputString {
<#
.SYNOPSIS
This function does the following things:
1. display an optional prompt message to the user (with timestamp, when $DisplayTimestampsInConsole is on)
2. collect and return the text input from the user as a string
3. Logs only the prompt, NOT the user input
.INPUTS
1. full physical path to the log file
2. prompt message (optional) - please do not include ":"
.OUTPUTS
User input as a string
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[String]
$LogFilePath,
[Parameter(Mandatory = $false)]
[String]
$PromptMessage
)
if ($PromptMessage) {
$promptMessageLogLine = "UserInterface-Prompt-SensitiveInput : " + $PromptMessage
Write-Log $LogFilePath $InfoMsg $promptMessageLogLine
}
$userFacingPromptMessage = Get-UserFacingMessage $PromptMessage
Read-Host -Prompt $userFacingPromptMessage
}
function Global:Append-DotsToLatestMessage {
<#
.SYNOPSIS
This function appends a number of dots to the last message displayed in the console
.INPUTS
Number of dots to add
.OUTPUTS
None
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[Int]
$NumberOfDots
)
if ($NumberOfDots -lt 0) {
throw "Error: cannot add negative number of dots to the message."
}
$numberAdded = 0;
while ($numberAdded -lt $NumberOfDots) {
Write-Host -NoNewline "."
$numberAdded ++
}
}
function Global:Show-SpinnerAnimation {
<#
.SYNOPSIS
This function shows a spinner animation in the PowerShell console
.INPUTS
Seconds to display the animation
.OUTPUTS
None
.EXAMPLE
$job = Start-Process $yourProcess
while ($job.Running) { Show-SpinnerAnimation 3 }
Write-Host " "
.NOTES
You can call a this function multiple times in a roll to have a continuous spin
After you are done with spinning, please invoke 'Write-Host " "' to make a new line
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[Int]
$DurationInSeconds
)
$prefix = Get-UserFacingMessage
$spinner = "/-\|/-\|"
$frame = 0
$count = 0
$limit = 10 * $DurationInSeconds # because 100 milliseconds per frame
$originalPosition = $Host.UI.RawUI.CursorPosition
while ($count -le $limit) {
$Host.UI.RawUI.CursorPosition = $originalPosition
$currentFrame = "`r$prefix" + $spinner[$frame]
Write-Host -NoNewline $currentFrame
Start-Sleep -Milliseconds 100
$frame++
$count++
if ($frame -ge $spinner.Length) {
$frame = 0
}
}
$Host.UI.RawUI.CursorPosition = $originalPosition
}
function Global:Get-IISServerInfoObject()
{
<#
.SYNOPSIS
Get list of objects with details of each website.
.INPUTS
None
.OUTPUTS
Returns object containing top-level IIS server information
objects from IIS applicationHost.config and administration.config.
IIS configurations are at %windir%\windows\system32\inetsrv\config
Return object contains these objects:
+--- Computer Name
+--- OS Version
+--- gac
+--- applicationHost
+--- webServer
+--- ftpServer
+--- location
+--- IIS versions
+--- appHost
+--- location
+--- admWebServer
+--- admModuleProviders
.EXAMPLE
$serverObj = Get-IISServerInfoObjects
#>
[CmdletBinding()]
[OutputType([psobject])]
param()
$windir = $Env:Windir
[hashtable]$resultObject = @{}
$computer = Get-WmiObject -Class Win32_ComputerSystem
$osVersion = $([System.Environment]::OSVersion.Version)
$resultObject.Add('computerName', $computer.name)
$resultObject.Add('osVersion', $osVersion)
$APP_HOST_CFG_FILE_PATH = $windir + "\system32\inetsrv\config\applicationHost.config"
$APP_HOST_XML_PATH = "configuration/system.applicationHost"
$WEB_SERVER_XML_PATH = "configuration/system.webServer"
$FTP_SERVER_XML_PATH = "configuration/system.ftpServer"
$LOCATION_XML_PATH = "configuration/location"
$INETSRV_WEBADMIN_DLL= $windir + "\system32\inetsrv\Microsoft.Web.Administration.dll"
$ADM_CFG_FILE_PATH = $windir + "\system32\inetsrv\config\administration.config"
$ADM_WEBSERVER_XML_PATH = "configuration/system.webServer"
$ADM_MODULE_PROVIDERS_XML_PATH = "configuration/moduleProviders"
if (!(Test-Path $APP_HOST_CFG_FILE_PATH -PathType Leaf)) {
Write-Output $APP_HOST_CFG_FILE_PATH
throw "ERROR: Cannot get Application Host Config"
}
if (!(Test-Path $INETSRV_WEBADMIN_DLL -PathType Leaf)) {
Write-Output $INETSRV_WEBADMIN_DLL
throw "ERROR: Cannot get web admin dll"
}
$appHost = Select-Xml -Path $APP_HOST_CFG_FILE_PATH -XPath $APP_HOST_XML_PATH | Select-Object -ExpandProperty Node
$resultObject.Add('appHost', $appHost)