-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy path3rd-Bootstrap_WindowsServer-Regacy.ps1
3388 lines (2768 loc) · 179 KB
/
3rd-Bootstrap_WindowsServer-Regacy.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
########################################################################################################################
#.SYNOPSIS
#
# Amazon EC2 Bootstrap Script - 3rd Bootstrap (Regacy)
#
#.DESCRIPTION
#
# Uses option settings to Windows Server Configuration
#
#.NOTES
#
# Target Windows Server OS Version and Processor Architecture (64bit Only)
#
# - 6.1 : Windows Server 2008 R2 (Microsoft Windows Server 2008 R2 SP1 [Datacenter Edition])
# [Windows_Server-2008-R2_SP1-Japanese-64Bit-Base-YYYY.MM.DD]
# [Windows_Server-2008-R2_SP1-English-64Bit-Base-YYYY.MM.DD]
#
# - 6.2 : Windows Server 2012 (Microsoft Windows Server 2012 [Standard Edition])
# [Windows_Server-2012-RTM-Japanese-64Bit-Base-YYYY.MM.DD]
# [Windows_Server-2012-RTM-English-64Bit-Base-YYYY.MM.DD]
#
# - 6.3 : Windows Server 2012 R2 (Microsoft Windows Server 2012 R2 [Standard Edition])
# [Windows_Server-2012-R2_RTM-Japanese-64Bit-Base-YYYY.MM.DD]
# [Windows_Server-2012-R2_RTM-English-64Bit-Base-YYYY.MM.DD]
#
# - 10.0 : Windows Server 2016 (Microsoft Windows Server 2016 [Datacenter Edition])
# [Windows_Server-2016-Japanese-Full-Base-YYYY.MM.DD]
# [Windows_Server-2016-English-Full-Base-YYYY.MM.DD]
#
# - 10.0 : Windows Server 2019 (Microsoft Windows Server 2019 [Datacenter Edition])
# [Windows_Server-2019-Japanese-Full-Base-YYYY.MM.DD]
# [Windows_Server-2019-English-Full-Base-YYYY.MM.DD]
#
# - 10.0 : Windows Server 2022 (Microsoft Windows Server 2022 [Datacenter Edition])
# [Windows_Server-2022-Japanese-Full-Base-YYYY.MM.DD]
# [Windows_Server-2022-English-Full-Base-YYYY.MM.DD]
#
########################################################################################################################
#-------------------------------------------------------------------------------
# Information of Windows Server
# - Windows Server
# https://docs.microsoft.com/ja-jp/windows-server/windows-server
#
# - Windows Server on AWS
# https://aws.amazon.com/jp/windows/
# http://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/
#
# - Windows Server AMI
# https://aws.amazon.com/jp/windows/resources/amis/
# https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/windows-ami-version-history.html
#-------------------------------------------------------------------------------
#-----------------------------------------------------------------------------------------------------------------------
# User Define Parameter
#-----------------------------------------------------------------------------------------------------------------------
# Set Script Parameter for Script (User Defined)
Set-Variable -Name FLAG_APP_INSTALL -Option Constant -Scope Script -Value "$TRUE"
Set-Variable -Name FLAG_APP_DOWNLOAD -Option Constant -Scope Script -Value "$TRUE"
# Set Script Parameter for Directory Name (User Defined)
Set-Variable -Name BASE_DIR -Option Constant -Scope Script "$Env:SystemDrive\EC2-Bootstrap"
Set-Variable -Name TOOL_DIR -Option Constant -Scope Script "$BASE_DIR\Tools"
Set-Variable -Name LOGS_DIR -Option Constant -Scope Script "$BASE_DIR\Logs"
Set-Variable -Name TEMP_DIR -Option Constant -Scope Script "$Env:SystemRoot\Temp"
# Set Script Parameter for Log File Name (User Defined)
Set-Variable -Name USERDATA_LOG -Option Constant -Scope Script "$TEMP_DIR\userdata.log"
Set-Variable -Name TRANSCRIPT_LOG -Option Constant -Scope Script "$LOGS_DIR\userdata-transcript.log"
# Set System Config File (sysprep)
Set-Variable -Name EC2Launchv2SysprepFile -Option Constant -Scope Script -Value "C:\ProgramData\Amazon\EC2Launch\sysprep\unattend.xml"
Set-Variable -Name EC2LaunchSysprepFile -Option Constant -Scope Script -Value "C:\ProgramData\Amazon\EC2-Windows\Launch\Sysprep\Unattend.xml"
Set-Variable -Name EC2ConfigSysprepFile -Option Constant -Scope Script -Value "C:\Program Files\Amazon\Ec2ConfigService\sysprep2008.xml"
# Set System & Application Config File (System Defined : Windows Server 2016, 2019)
Set-Variable -Name EC2LaunchFile -Option Constant -Scope Script -Value "C:\ProgramData\Amazon\EC2-Windows\Launch\Config\LaunchConfig.json"
# Set System & Application Config File (System Defined : Windows Server 2008 R2, 2012, 2012 R2)
Set-Variable -Name EC2ConfigFile -Option Constant -Scope Script -Value "C:\Program Files\Amazon\Ec2ConfigService\Settings\Config.xml"
# Set System & Application Config File (System Defined : Windows Server 2008 R2, 2012, 2012 R2, 2016, 2019)
Set-Variable -Name EC2Launchv2File -Option Constant -Scope Script -Value "C:\ProgramData\Amazon\EC2Launch\config\agent-config.yml"
# Set System & Application Log File (System Defined : All Windows Server)
Set-Variable -Name SSMAgentLogFile -Option Constant -Scope Script -Value "C:\ProgramData\Amazon\SSM\Logs\amazon-ssm-agent.log"
########################################################################################################################
#
# Windows Bootstrap Common function
#
########################################################################################################################
function Format-Message {
param([string]$message)
$timestamp = Get-Date -Format "yyyy/MM/dd HH:mm:ss.fffffff zzz"
"$timestamp - $message"
} # end function Format-Message
function Write-Log {
param([string]$message, $log = $USERDATA_LOG)
# Messages to log files
Format-Message $message | Out-File $log -Append -Force
# Messages to the console host (Uses for Script Testing)
Format-Message $message | Write-Host -ForegroundColor Green -ErrorAction SilentlyContinue
} # end function Write-Log
function Write-LogSeparator {
param([string]$message)
Write-Log "#------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------"
Write-Log ("# Script Executetion Step : " + $message)
Write-Log "#------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------"
} # end function Write-LogSeparator
function New-Directory {
param([string]$dir)
if (!(Test-Path -Path $dir)) {
Write-Log "# Creating directory : $dir"
New-Item -Path $dir -ItemType Directory -Force
Start-Sleep -Seconds 1
}
} # end function New-Directory
function Convert-SCSITargetIdToDeviceName {
param([int]$SCSITargetId)
If ($SCSITargetId -eq 0) {
return "sda1"
}
$deviceName = "xvd"
If ($SCSITargetId -gt 25) {
$deviceName += [char](0x60 + [int]($SCSITargetId / 26))
}
$deviceName += [char](0x61 + $SCSITargetId % 26)
return $deviceName
} # end Convert-SCSITargetIdToDeviceName
function Set-TimeZoneCompatible {
param(
[Parameter(ValueFromPipeline = $False, ValueFromPipelineByPropertyName = $True, Mandatory = $False)]
[ValidateSet("Dateline Standard Time", "UTC-11", "Hawaiian Standard Time", "Alaskan Standard Time", "Pacific Standard Time (Mexico)", "Pacific Standard Time", "US Mountain Standard Time", "Mountain Standard Time (Mexico)", "Mountain Standard Time", "Central America Standard Time", "Central Standard Time", "Central Standard Time (Mexico)", "Canada Central Standard Time", "SA Pacific Standard Time", "Eastern Standard Time", "US Eastern Standard Time", "Venezuela Standard Time", "Paraguay Standard Time", "Atlantic Standard Time", "Central Brazilian Standard Time", "SA Western Standard Time", "Pacific SA Standard Time", "Newfoundland Standard Time", "E. South America Standard Time", "Argentina Standard Time", "SA Eastern Standard Time", "Greenland Standard Time", "Montevideo Standard Time", "Bahia Standard Time", "UTC-02", "Mid-Atlantic Standard Time", "Azores Standard Time", "Cape Verde Standard Time", "Morocco Standard Time", "UTC", "GMT Standard Time", "Greenwich Standard Time", "W. Europe Standard Time", "Central Europe Standard Time", "Romance Standard Time", "Central European Standard Time", "W. Central Africa Standard Time", "Namibia Standard Time", "Jordan Standard Time", "GTB Standard Time", "Middle East Standard Time", "Egypt Standard Time", "Syria Standard Time", "E. Europe Standard Time", "South Africa Standard Time", "FLE Standard Time", "Turkey Standard Time", "Israel Standard Time", "Arabic Standard Time", "Kaliningrad Standard Time", "Arab Standard Time", "E. Africa Standard Time", "Iran Standard Time", "Arabian Standard Time", "Azerbaijan Standard Time", "Russian Standard Time", "Mauritius Standard Time", "Georgian Standard Time", "Caucasus Standard Time", "Afghanistan Standard Time", "Pakistan Standard Time", "West Asia Standard Time", "India Standard Time", "Sri Lanka Standard Time", "Nepal Standard Time", "Central Asia Standard Time", "Bangladesh Standard Time", "Ekaterinburg Standard Time", "Myanmar Standard Time", "SE Asia Standard Time", "N. Central Asia Standard Time", "China Standard Time", "North Asia Standard Time", "Singapore Standard Time", "W. Australia Standard Time", "Taipei Standard Time", "Ulaanbaatar Standard Time", "North Asia East Standard Time", "Tokyo Standard Time", "Korea Standard Time", "Cen. Australia Standard Time", "AUS Central Standard Time", "E. Australia Standard Time", "AUS Eastern Standard Time", "West Pacific Standard Time", "Tasmania Standard Time", "Yakutsk Standard Time", "Central Pacific Standard Time", "Vladivostok Standard Time", "New Zealand Standard Time", "UTC+12", "Fiji Standard Time", "Magadan Standard Time", "Tonga Standard Time", "Samoa Standard Time")]
[ValidateNotNullOrEmpty()]
[string]$TimeZone = "Tokyo Standard Time"
)
$process = New-Object System.Diagnostics.Process
$process.StartInfo.WindowStyle = "Hidden"
$process.StartInfo.FileName = "tzutil.exe"
$process.StartInfo.Arguments = "/s `"$TimeZone`""
$process.Start() | Out-Null
} # end function Set-TimeZoneCompatible
########################################################################################################################
#
# Windows Bootstrap Individual requirement function
# [Dependent on function]
# - Convert-SCSITargetIdToDeviceName
# - Write-Log
#
########################################################################################################################
function Get-AmazonMachineImageInformation {
Set-Variable -Name AMIRegistry -Option Constant -Scope Local -Value "HKLM:\SOFTWARE\Amazon\MachineImage"
if (Test-Path $AMIRegistry) {
$AMIRegistryValue = Get-ItemProperty -Path $AMIRegistry -ErrorAction SilentlyContinue
$AmiOriginalVersion = $AMIRegistryValue.AMIVersion
$AmiOriginalName = $AMIRegistryValue.AMIName
# Write the information to the Log Files
Write-Log "# [AWS - AMI] Windows - AMI Origin Version : $AmiOriginalVersion"
Write-Log "# [AWS - AMI] Windows - AMI Origin Name : $AmiOriginalName"
}
} # end function Get-AmazonMachineImageInformation
function Get-AmazonMachineInformation {
# Get System BIOS Firmware Type
if (Get-Command -CommandType Cmdlet | Where-Object { $_.Name -eq "Get-ComputerInfo" }) {
$BiosFirmwareType = (Get-ComputerInfo).BiosFirmwareType
# Identify System BIOS Firmware Type
if ($BiosFirmwareType -eq "Uefi") {
Write-Log "# [AWS - EC2] Hardware - System BIOS Firmware Type : [UEFI] - $BiosFirmwareType"
}
elseif ($BiosFirmwareType -eq "Bios") {
Write-Log "# [AWS - EC2] Hardware - System BIOS Firmware Type : [BIOS] - $BiosFirmwareType"
}
else {
Write-Log "# [AWS - EC2] Hardware - System BIOS Firmware Type : [Unidentified] - $BiosFirmwareType"
}
}
# Get System BIOS Information
Set-Variable -Name BiosRegistry -Option Constant -Scope Local -Value "HKLM:\HARDWARE\DESCRIPTION\System"
if (Test-Path $BiosRegistry) {
$BiosRegistryValue = Get-ItemProperty -Path $BiosRegistry -ErrorAction SilentlyContinue
$SystemBiosVersion = $BiosRegistryValue.SystemBiosVersion
# Write the information to the Log Files
Write-Log "# [AWS - EC2] Hardware - System BIOS Revision : $SystemBiosVersion"
}
# Get System CPU Information
Set-Variable -Name CpuRegistry -Option Constant -Scope Local -Value "HKLM:\HARDWARE\DESCRIPTION\System\CentralProcessor\0"
if (Test-Path $CpuRegistry) {
$CpuRegistryValue = Get-ItemProperty -Path $CpuRegistry -ErrorAction SilentlyContinue
$CpuVendorIdentifier = $CpuRegistryValue.VendorIdentifier
$CpuProcessorName = $CpuRegistryValue.ProcessorNameString
# Write the information to the Log Files
Write-Log "# [AWS - EC2] Hardware - CPU Vendor Information : $CpuVendorIdentifier"
Write-Log "# [AWS - EC2] Hardware - CPU Model Information : $CpuProcessorName"
}
# Get Windows RegisteredOrganization & RegisteredOwner Information
Set-Variable -Name Ec2Registry -Option Constant -Scope Local -Value "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion"
if (Test-Path $Ec2Registry) {
$Ec2RegistryValue = Get-ItemProperty -Path $Ec2Registry -ErrorAction SilentlyContinue
$Ec2RegisteredOrganization = $Ec2RegistryValue.RegisteredOrganization
$Ec2RegisteredOwner = $Ec2RegistryValue.RegisteredOwner
# Write the information to the Log Files
Write-Log "# [AWS - EC2] Windows - RegisteredOrganization : $Ec2RegisteredOrganization"
Write-Log "# [AWS - EC2] Windows - RegisteredOwner : $Ec2RegisteredOwner"
}
} # end function Get-AmazonMachineInformation
function Get-CustomizeEc2InstanceMetadata {
#--------------------------------------------------------------------------------------
# Get AWS Instance MetaData Service (IMDS v1, v2)
# https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/configuring-instance-metadata-service.html
# https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/instancedata-data-retrieval.html
#--------------------------------------------------------------------------------------
# Set Initialize Parameter
Set-Variable -Name Token -Scope Script -Value ($Null)
Set-Variable -Name Az -Scope Script -Value ($Null)
Set-Variable -Name AzId -Scope Script -Value ($Null)
Set-Variable -Name Region -Scope Script -Value ($Null)
Set-Variable -Name InstanceId -Scope Script -Value ($Null)
Set-Variable -Name InstanceType -Scope Script -Value ($Null)
Set-Variable -Name PrivateIp -Scope Script -Value ($Null)
Set-Variable -Name AmiId -Scope Script -Value ($Null)
Set-Variable -Name RoleArn -Scope Script -Value ($Null)
Set-Variable -Name RoleName -Scope Script -Value ($Null)
Set-Variable -Name StsCredential -Scope Script -Value ($Null)
Set-Variable -Name StsAccessKeyId -Scope Script -Value ($Null)
Set-Variable -Name StsSecretAccessKey -Scope Script -Value ($Null)
Set-Variable -Name StsToken -Scope Script -Value ($Null)
Set-Variable -Name AwsAccountId -Scope Script -Value ($Null)
# Getting an Instance Metadata Service v2 (IMDS v2) token
$Token = $(Invoke-RestMethod -Headers @{"X-aws-ec2-metadata-token-ttl-seconds" = "21600"} -Method PUT 'http://169.254.169.254/latest/api/token')
if ($Token) {
#-----------------------------------------------------------------------
# Retrieving Metadata Using the Instance Metadata Service v2 (IMDS v2)
#-----------------------------------------------------------------------
Write-Log "# [AWS - EC2] Retrieving Metadata Using the Instance Metadata Service v2 (IMDS v2)"
# AWS Instance Metadata
Set-Variable -Name Az -Scope Script -Value (Invoke-RestMethod -Headers @{"X-aws-ec2-metadata-token" = $token} -Method GET -Uri "http://169.254.169.254/latest/meta-data/placement/availability-zone")
Set-Variable -Name AzId -Scope Script -Value (Invoke-RestMethod -Headers @{"X-aws-ec2-metadata-token" = $token} -Method GET -Uri "http://169.254.169.254/latest/meta-data/placement/availability-zone-id")
Set-Variable -Name Region -Scope Script -Value (Invoke-RestMethod -Headers @{"X-aws-ec2-metadata-token" = $token} -Method GET -Uri "http://169.254.169.254/latest/meta-data/placement/region")
Set-Variable -Name InstanceId -Scope Script -Value (Invoke-RestMethod -Headers @{"X-aws-ec2-metadata-token" = $token} -Method GET -Uri "http://169.254.169.254/latest/meta-data/instance-id")
Set-Variable -Name InstanceType -Scope Script -Value (Invoke-RestMethod -Headers @{"X-aws-ec2-metadata-token" = $token} -Method GET -Uri "http://169.254.169.254/latest/meta-data/instance-type")
Set-Variable -Name PrivateIp -Scope Script -Value (Invoke-RestMethod -Headers @{"X-aws-ec2-metadata-token" = $token} -Method GET -Uri "http://169.254.169.254/latest/meta-data/local-ipv4")
Set-Variable -Name AmiId -Scope Script -Value (Invoke-RestMethod -Headers @{"X-aws-ec2-metadata-token" = $token} -Method GET -Uri "http://169.254.169.254/latest/meta-data/ami-id")
# IAM Role & STS Information
Set-Variable -Name RoleArn -Scope Script -Value ((Invoke-WebRequest -Headers @{"X-aws-ec2-metadata-token" = $token} -Method GET -Uri "http://169.254.169.254/latest/meta-data/iam/info" -UseBasicParsing) | ConvertFrom-Json).InstanceProfileArn
Set-Variable -Name RoleName -Scope Script -Value ($RoleArn -split "/" | Select-Object -Index 1)
if ($RoleName) {
Set-Variable -Name StsCredential -Scope Script -Value ((Invoke-WebRequest -Headers @{"X-aws-ec2-metadata-token" = $token} -Method GET -Uri ("http://169.254.169.254/latest/meta-data/iam/security-credentials/" + $RoleName) -UseBasicParsing) | ConvertFrom-Json)
Set-Variable -Name StsAccessKeyId -Scope Script -Value $StsCredential.AccessKeyId
Set-Variable -Name StsSecretAccessKey -Scope Script -Value $StsCredential.SecretAccessKey
Set-Variable -Name StsToken -Scope Script -Value $StsCredential.Token
}
# AWS Account ID
Set-Variable -Name AwsAccountId -Scope Script -Value ((Invoke-WebRequest -Headers @{"X-aws-ec2-metadata-token" = $token} -Method GET -Uri "http://169.254.169.254/latest/dynamic/instance-identity/document" -UseBasicParsing) | ConvertFrom-Json).accountId
}
else {
#-----------------------------------------------------------------------
# Retrieving Metadata Using the Instance Metadata Service v1 (IMDS v1)
#-----------------------------------------------------------------------
Write-Log "# [AWS - EC2] Retrieving Metadata Using the Instance Metadata Service v1 (IMDS v1)"
# AWS Instance Metadata
Set-Variable -Name Az -Scope Script -Value (Invoke-RestMethod -Uri "http://169.254.169.254/latest/meta-data/placement/availability-zone")
Set-Variable -Name AzId -Scope Script -Value (Invoke-RestMethod -Uri "http://169.254.169.254/latest/meta-data/placement/availability-zone-id")
Set-Variable -Name Region -Scope Script -Value (Invoke-RestMethod -Uri "http://169.254.169.254/latest/meta-data/placement/region")
Set-Variable -Name InstanceId -Scope Script -Value (Invoke-RestMethod -Uri "http://169.254.169.254/latest/meta-data/instance-id")
Set-Variable -Name InstanceType -Scope Script -Value (Invoke-RestMethod -Uri "http://169.254.169.254/latest/meta-data/instance-type")
Set-Variable -Name PrivateIp -Scope Script -Value (Invoke-RestMethod -Uri "http://169.254.169.254/latest/meta-data/local-ipv4")
Set-Variable -Name AmiId -Scope Script -Value (Invoke-RestMethod -Uri "http://169.254.169.254/latest/meta-data/ami-id")
# IAM Role & STS Information
Set-Variable -Name RoleArn -Scope Script -Value ((Invoke-WebRequest -Uri "http://169.254.169.254/latest/meta-data/iam/info" -UseBasicParsing) | ConvertFrom-Json).InstanceProfileArn
Set-Variable -Name RoleName -Scope Script -Value ($RoleArn -split "/" | Select-Object -Index 1)
if ($RoleName) {
Set-Variable -Name StsCredential -Scope Script -Value ((Invoke-WebRequest -Uri ("http://169.254.169.254/latest/meta-data/iam/security-credentials/" + $RoleName) -UseBasicParsing) | ConvertFrom-Json)
Set-Variable -Name StsAccessKeyId -Scope Script -Value $StsCredential.AccessKeyId
Set-Variable -Name StsSecretAccessKey -Scope Script -Value $StsCredential.SecretAccessKey
Set-Variable -Name StsToken -Scope Script -Value $StsCredential.Token
}
# AWS Account ID
Set-Variable -Name AwsAccountId -Scope Script -Value ((Invoke-WebRequest -Uri "http://169.254.169.254/latest/dynamic/instance-identity/document" -UseBasicParsing) | ConvertFrom-Json).accountId
}
# Logging AWS Instance Metadata
Write-Log "# [AWS - EC2] Region : $Region"
Write-Log "# [AWS - EC2] Availability Zone : $Az"
Write-Log "# [AWS - EC2] Availability Zone ID: $AzId"
Write-Log "# [AWS - EC2] Instance ID : $InstanceId"
Write-Log "# [AWS - EC2] Instance Type : $InstanceType"
Write-Log "# [AWS - EC2] VPC Private IP Address(IPv4) : $PrivateIp"
Write-Log "# [AWS - EC2] Amazon Machine Images ID : $AmiId"
if ($RoleName) {
Write-Log "# [AWS - EC2] Instance Profile ARN : $RoleArn"
Write-Log "# [AWS - EC2] IAM Role Name : $RoleName"
}
} # end function Get-CustomizeEc2InstanceMetadata
function Get-DotNetFrameworkVersion {
# Get Installed .NET Framework Version
$dotnet_versions = Get-ChildItem -Path 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP' -Recurse | Get-ItemProperty -Name Version -EA 0 | Where-Object -FilterScript { $_.PSChildName -match '^(?!S)\p{L}' } | Select-Object -Property PSChildName, Version
foreach ($dotnet_version in $dotnet_versions) {
# Write the information to the Log Files
Write-Log ("# [Windows] .NET Framework Information : v{0} - Profile : {1} " -f $dotnet_version.Version, $dotnet_version.PSChildName)
}
} # end function Get-DotNetFrameworkVersion
function Get-EbsVolumesMappingInformation {
#--------------------------------------------------------------------------------------
# Listing the Disks Using Windows PowerShell
# https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/ec2-windows-volumes.html#windows-list-disks
#--------------------------------------------------------------------------------------
# Set Initialize Parameter
Set-Variable -Name BlockDeviceName -Scope Script -Value ($Null)
Set-Variable -Name BlockDeviceMappings -Scope Script -Value ($Null)
Set-Variable -Name EBSVolumeList -Scope Script -Value ($Null)
Set-Variable -Name EBSVolumeLists -Scope Script -Value ($Null)
Set-Variable -Name VirtualDevice -Scope Script -Value ($Null)
Set-Variable -Name VirtualDeviceMap -Scope Script -Value ($Null)
Set-Variable -Name VolumeName -Scope Script -Value ($Null)
Set-Variable -Name DeviceName -Scope Script -Value ($Null)
# Test Cmdlet
if (Get-Command -CommandType Cmdlet | Where-Object { $_.Name -eq "Get-EC2InstanceMetadata" }) {
Try {
Get-EC2InstanceMetadata -ListCategory
}
Catch {
Write-Host "Could not access the instance Metadata using AWS Get-EC2Instance CMDLet. Verify that you provided your access keys or assigned an IAM role with adequate permissions." -ForegroundColor Yellow
}
}
# List the Windows disks
[string[]]$array1 = @()
[string[]]$array2 = @()
[string[]]$array3 = @()
[string[]]$array4 = @()
Get-WmiObject Win32_Volume | Select-Object Name, DeviceID | ForEach-Object {
$array1 += $_.Name
$array2 += $_.DeviceID
}
$i = 0
While ($i -ne ($array2.Count)) {
$array3 += ((Get-Volume -Path $array2[$i] | Get-Partition | Get-Disk).SerialNumber) -replace "_[^ ]*$" -replace "vol", "vol-"
$array4 += ((Get-Volume -Path $array2[$i] | Get-Partition | Get-Disk).FriendlyName)
$i ++
}
[array[]]$array = $array1, $array2, $array3, $array4
Try {
# Getting an Instance Metadata Service v2 (IMDS v2) token
$Token = $(Invoke-RestMethod -Headers @{"X-aws-ec2-metadata-token-ttl-seconds" = "21600"} -Method PUT 'http://169.254.169.254/latest/api/token')
if ($Token) {
#-----------------------------------------------------------------------
# Retrieving Metadata Using the Instance Metadata Service v2 (IMDS v2)
#-----------------------------------------------------------------------
Write-Log "# [AWS - EC2] Retrieving Metadata Using the Instance Metadata Service v2 (IMDS v2)"
# InstanceId
if ( [string]::IsNullOrEmpty($InstanceId) ) {
Set-Variable -Name InstanceId -Scope Script -Value (Invoke-RestMethod -Headers @{"X-aws-ec2-metadata-token" = $token} -Method GET -Uri "http://169.254.169.254/latest/meta-data/instance-id")
}
# Region
if ( [string]::IsNullOrEmpty($Region) ) {
Set-Variable -Name Region -Scope Script -Value (Invoke-RestMethod -Headers @{"X-aws-ec2-metadata-token" = $token} -Method GET -Uri "http://169.254.169.254/latest/meta-data/placement/region")
}
}
else {
#-----------------------------------------------------------------------
# Retrieving Metadata Using the Instance Metadata Service v1 (IMDS v1)
#-----------------------------------------------------------------------
Write-Log "# [AWS - EC2] Retrieving Metadata Using the Instance Metadata Service v1 (IMDS v1)"
# InstanceId
if ( [string]::IsNullOrEmpty($InstanceId) ) {
Set-Variable -Name InstanceId -Scope Script -Value (Invoke-RestMethod -Uri "http://169.254.169.254/latest/meta-data/instance-id")
}
# Region
if ( [string]::IsNullOrEmpty($Region) ) {
Set-Variable -Name Region -Scope Script -Value (Invoke-RestMethod -Uri "http://169.254.169.254/latest/meta-data/placement/region")
}
}
}
Catch {
Write-Host "Could not access the instance Metadata using Invoke-RestMethod CMDLet. Verify you have AWSPowershell SDK version '3.1.73.0' or greater installed and Metadata is enabled for this instance." -ForegroundColor Yellow
}
Try {
# Get the volumes attached to this instance
$BlockDeviceMappings = (Get-EC2Instance -Region $Region -Instance $InstanceId).Instances.BlockDeviceMappings
}
Catch {
Write-Host "Could not access the instance Metadata using AWS Get-EC2Instance CMDLet. Verify that you provided your access keys or assigned an IAM role with adequate permissions." -ForegroundColor Yellow
}
Try {
# Get the block-device-mapping
$VirtualDeviceMap = (Get-EC2InstanceMetadata -Category "BlockDeviceMapping").GetEnumerator() | Where-Object { $_.Key -ne "ami" }
}
Catch {
Write-Host "Could not access the AWS API using AWS Get-EC2InstanceMetadata CMDLet, therefore, VolumeId is not available. Verify that you provided your access keys or assigned an IAM role with adequate permissions." -ForegroundColor Yellow
}
# Get EBS volumes and Ephemeral disks Information
$EBSVolumeLists = Get-Disk | ForEach-Object {
$DriveLetter = $null
$VolumeName = $null
$VirtualDevice = $null
$DeviceName = $_.FriendlyName
$DiskDrive = $_
$Disk = $_.Number
$Partitions = $_.NumberOfPartitions
$EbsVolumeID = $_.SerialNumber -replace "_[^ ]*$" -replace "vol", "vol-"
if ($Partitions -ge 1) {
$PartitionsData = Get-Partition -DiskId $_.Path
$DriveLetter = $PartitionsData.DriveLetter | Where-object { $_ -notin @("", $null) }
$VolumeName = (Get-PSDrive | Where-Object { $_.Name -in @($DriveLetter) }).Description | Where-object { $_ -notin @("", $null) }
}
if ($DiskDrive.path -like "*PROD_PVDISK*") {
$BlockDeviceName = Convert-SCSITargetIdToDeviceName((Get-WmiObject -Class Win32_Diskdrive | Where-Object { $_.DeviceID -eq ("\\.\PHYSICALDRIVE" + $DiskDrive.Number) }).SCSITargetId)
$BlockDeviceName = "/dev/" + $BlockDeviceName
$BlockDevice = $BlockDeviceMappings | Where-Object { $BlockDeviceName -like "*" + $_.DeviceName + "*" }
$EbsVolumeID = $BlockDevice.Ebs.VolumeId
$VirtualDevice = ($VirtualDeviceMap.GetEnumerator() | Where-Object { $_.Value -eq $BlockDeviceName }).Key | Select-Object -First 1
}
elseif ($DiskDrive.path -like "*PROD_AMAZON_EC2_NVME*") {
$BlockDeviceName = (Get-EC2InstanceMetadata -Category "BlockDeviceMapping").ephemeral((Get-WmiObject -Class Win32_Diskdrive | Where-Object { $_.DeviceID -eq ("\\.\PHYSICALDRIVE" + $DiskDrive.Number) }).SCSIPort - 2)
$BlockDevice = $null
$VirtualDevice = ($VirtualDeviceMap.GetEnumerator() | Where-Object { $_.Value -eq $BlockDeviceName }).Key | Select-Object -First 1
}
elseif ($DiskDrive.path -like "*PROD_AMAZON*") {
if ($DriveLetter -match '[^a-zA-Z0-9]') {
$i = 0
While ($i -ne ($array3.Count)) {
if ($array[2][$i] -eq $EbsVolumeID) {
$DriveLetter = $array[0][$i]
$DeviceName = $array[3][$i]
}
$i ++
}
}
$BlockDevice = ""
$BlockDeviceName = ($BlockDeviceMappings | Where-Object { $_.ebs.VolumeId -eq $EbsVolumeID }).DeviceName
}
elseif ($DiskDrive.path -like "*NETAPP*") {
if ($DriveLetter -match '[^a-zA-Z0-9]') {
$i = 0
While ($i -ne ($array3.Count)) {
if ($array[2][$i] -eq $EbsVolumeID) {
$DriveLetter = $array[0][$i]
$DeviceName = $array[3][$i]
}
$i ++
}
}
$EbsVolumeID = "FSxN Volume"
$BlockDevice = ""
$BlockDeviceName = ($BlockDeviceMappings | Where-Object { $_.ebs.VolumeId -eq $EbsVolumeID }).DeviceName
}
else {
$BlockDeviceName = $null
$BlockDevice = $null
}
New-Object PSObject -Property @{
Disk = $Disk;
Partitions = $Partitions;
DriveLetter = if ($null -eq $DriveLetter) { "N/A" } else { $DriveLetter };
EbsVolumeId = if ($null -eq $EbsVolumeID) { "N/A" } else { $EbsVolumeID };
Device = if ($null -eq $BlockDeviceName) { "N/A" } else { $BlockDeviceName };
VirtualDevice = if ($null -eq $VirtualDevice) { "N/A" } else { $VirtualDevice };
VolumeName = if ($null -eq $VolumeName) { "N/A" } else { $VolumeName };
DeviceName = if ($null -eq $DeviceName) { "N/A" } else { $DeviceName };
}
} | Sort-Object Disk | Select-Object -Property Disk, Partitions, DriveLetter, EbsVolumeId, Device, VirtualDevice, DeviceName, VolumeName
foreach ($EBSVolumeList in $EBSVolumeLists) {
if ($EBSVolumeList) {
# Write the information to the Log Files
Write-Log ("# [AWS - EBS] Windows - [Disk - {0}] [Partitions - {1}] [DriveLetter - {2}] [EbsVolumeId - {3}] [Device - {4}] [VirtualDevice - {5}] [DeviceName - {6}] [VolumeName - {7}]" -f $EBSVolumeList.Disk, $EBSVolumeList.Partitions, $EBSVolumeList.DriveLetter, $EBSVolumeList.EbsVolumeId, $EBSVolumeList.Device, $EBSVolumeList.VirtualDevice, $EBSVolumeList.DeviceName, $EBSVolumeList.VolumeName)
}
}
} # end Get-EbsVolumesMappingInformation
function Get-Ec2ConfigVersion {
#--------------------------------------------------------------------------------------
# Configuring a Windows Instance Using the EC2Config Service
# http://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/UsingConfig_WinAMI.html
#--------------------------------------------------------------------------------------
# Set Initialize Parameter
Set-Variable -Name EC2ConfigInformation -Scope Script -Value ($Null)
Set-Variable -Name Ec2ConfigVersion -Scope Script -Value ($Null)
# Get EC2Config Version
$EC2ConfigInformation = $(Get-WmiObject -Class Win32_Product | Select-Object Name, Version | Where-Object { $_.Name -eq "EC2ConfigService" })
if ($EC2ConfigInformation) {
$Ec2ConfigVersion = $EC2ConfigInformation.Version
}
# Write the information to the Log Files
if ($Ec2ConfigVersion) {
Write-Log "# [Windows] Amazon EC2 Windows Utility Information - Amazon EC2Config Version : $Ec2ConfigVersion"
}
} # end Get-Ec2ConfigVersion
function Get-Ec2LaunchVersion {
#--------------------------------------------------------------------------------------
# Configuring a Windows Instance Using EC2Launch
# https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/ec2launch.html
#--------------------------------------------------------------------------------------
# Set Initialize Parameter
Set-Variable -Name Ec2LaunchModuleConfig -Option Constant -Scope Local -Value "C:\ProgramData\Amazon\EC2-Windows\Launch\Module\Ec2Launch.psd1"
Set-Variable -Name Ec2LaunchVersion -Scope Script -Value ($Null)
# Get EC2Launch Version
if (Test-Path $Ec2LaunchModuleConfig) {
Import-Module -Name "C:\ProgramData\Amazon\EC2-Windows\Launch\Module\Ec2Launch.psd1"
$Ec2LaunchVersion = (Get-Module EC2Launch).Version.ToString()
# Write the information to the Log Files
if ($Ec2LaunchVersion) {
Write-Log "# [Windows] Amazon EC2 Windows Utility Information - Amazon EC2Launch Version : $Ec2LaunchVersion"
}
}
} # end Get-Ec2LaunchVersion
function Get-Ec2LaunchV2Version {
#--------------------------------------------------------------------------------------
# Configuring a Windows Instance Using EC2Launch
# https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/ec2launch-v2.html
#--------------------------------------------------------------------------------------
# Set Initialize Parameter
Set-Variable -Name Ec2LaunchV2Information -Scope Script -Value ($Null)
Set-Variable -Name Ec2LaunchV2Version -Scope Script -Value ($Null)
# Get EC2Launch Version
$Ec2LaunchV2Information = $(Get-WmiObject -Class Win32_Product | Select-Object Name, Version | Where-Object { $_.Name -eq "Amazon EC2Launch" })
if ($Ec2LaunchV2Information) {
$Ec2LaunchV2Version = $Ec2LaunchV2Information.Version
}
# Write the information to the Log Files
if ($Ec2LaunchV2Version) {
Write-Log "# [Windows] Amazon EC2 Windows Utility Information - Amazon EC2Launch v2 Version : $Ec2LaunchV2Version"
}
} # end Get-Ec2LaunchV2Version
function Get-Ec2SystemManagerAgentVersion {
#--------------------------------------------------------------------------------------
# Amazon EC2 Systems Manager
# https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/systems-manager.html
#--------------------------------------------------------------------------------------
# Set Initialize Parameter
Set-Variable -Name SSMAgentRegistry -Option Constant -Scope Local -Value "HKLM:\SYSTEM\CurrentControlSet\Services\AmazonSSMAgent"
Set-Variable -Name SSMAgentUninstallRegistry -Option Constant -Scope Local -Value "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{B1A3AC35-A431-4C8C-9D21-E2CA92047F76}"
Set-Variable -Name SsmAgentVersion -Scope Script -Value ($Null)
if (Test-Path $SSMAgentRegistry) {
$SSMAgentRegistryValue = Get-ItemProperty -Path $SSMAgentRegistry -ErrorAction SilentlyContinue
$SsmAgentVersion = $SSMAgentRegistryValue.Version
}
if (-not $SsmAgentVersion -and (Test-Path $SSMAgentUninstallRegistry)) {
$SSMAgentRegistryValue = Get-ItemProperty -Path $SSMAgentUninstallRegistry -ErrorAction SilentlyContinue
$SsmAgentVersion = $SSMAgentRegistryValue.DisplayVersion
}
# Write the information to the Log Files
if ($SsmAgentVersion) {
Write-Log "# [Windows] Amazon EC2 Windows Utility Information - Amazon SSM Agent Version : $SsmAgentVersion"
}
} # end function Get-Ec2SystemManagerAgentVersion
function Get-NetAdapterBindingInformation {
# Get NetAdapter Binding Component
$NetAdapterBindings = Get-NetAdapterBinding | Select-Object -Property Name, DisplayName, ComponentID, Enabled
foreach ($NetAdapterBinding in $NetAdapterBindings) {
# Write the information to the Log Files
Write-Log ("# [Windows - OS Settings] NetAdapterBinding : [Name - {0}] [DisplayName - {1}] [ComponentID - {2}] [Enabled - {3}]" -f $NetAdapterBinding.Name, $NetAdapterBinding.DisplayName, $NetAdapterBinding.ComponentID, $NetAdapterBinding.Enabled)
}
} # end Get-NetAdapterBindingInformation
function Get-NetFirewallProfileInformation {
# Get Net Firewall Profile
$FirewallProfiles = Get-NetFirewallProfile | Select-Object -Property Name, Enabled
foreach ($FirewallProfile in $FirewallProfiles) {
# Write the information to the Log Files
Write-Log ("# [Windows - OS Settings] NetFirewallProfile : [Name - {0}] [Enabled - {1}]" -f $FirewallProfile.Name, $FirewallProfile.Enabled)
}
} # end Get-NetFirewallProfileInformation
function Get-ScriptExecuteByAccount {
# Get PowerShell Script Execution UserName
Set-Variable -Name ScriptExecuteByAccountInformation -Scope Local -Value ([Security.Principal.WindowsIdentity]::GetCurrent())
Set-Variable -Name ScriptExecuteByAccountName -Scope Local -Value ($ScriptExecuteByAccountInformation.Name -split "\" , 0 , "simplematch" | Select-Object -Index 1)
# Test of administrative privileges
Set-Variable -Name CheckAdministrator -Scope Local -Value (([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
# Write the information to the Log Files
if ($ScriptExecuteByAccountName) {
Write-Log ("# [Windows] Powershell Script Execution Username : " + ($ScriptExecuteByAccountName))
if ($CheckAdministrator -eq $true) {
Write-Log "# [Windows] Bootstrap scripts run with the privileges of the administrator"
}
else {
Write-Log "# [Windows] Bootstrap scripts run with the privileges of the non-administrator"
}
}
} # end Get-ScriptExecuteByAccount
function Get-PageFileInformation {
# Get PageFile Information
$pagefiles = Get-WmiObject -Class Win32_PageFileusage | Select-Object -Property Name, CurrentUsage, AllocatedBaseSize, PeakUsage, InstallDate
foreach ($pagefile in $pagefiles) {
# Write the information to the Log Files
Write-Log ("# [Windows - OS Settings] Page File : [Name - {0}] [CurrentUsage - {1}] [AllocatedBaseSize - {2}] [PeakUsage - {3}]" -f $pagefile.Name, $pagefile.CurrentUsage, $pagefile.AllocatedBaseSize, $pagefile.PeakUsage)
}
} # end Get-PageFileInformation
function Get-PowerPlanInformation {
# Get PowerPlan Settings
$powerplans = Get-WmiObject -Namespace root\cimv2\power -Class win32_PowerPlan | Select-Object ElementName, IsActive, Description
foreach ($powerplan in $powerplans) {
if ($powerplan | Where-Object { $_.IsActive -eq $True }) {
# Write the information to the Log Files
Write-Log ("# [Windows - OS Settings] PowerPlan : [ElementName - {0}] [IsActive - {1}] [Description - {2}]" -f $powerplan.ElementName, $powerplan.IsActive, $powerplan.Description)
}
}
} # end Get-PowerPlanInformation
function Get-PowerShellVerson {
# Get PowerShell Environment Information
$PowerShellVersion = $PSVersionTable.PSVersion.ToString()
$PowerShellClrVersion = $PSVersionTable.CLRVersion.ToString()
# Write the information to the Log Files
Write-Log ("# [Windows] PowerShell Information : [Version - {0}] [CLR Version - {1}]" -f $PowerShellVersion, $PowerShellClrVersion)
} # end Get-PowerShellVerson
function Get-WindowsDriverInformation {
$win_drivers = Get-WindowsDriver -Online | Where-Object { $_.OriginalFileName -like '*xenvbd*' -or $_.ClassName -eq 'Net' -and `
($_.ProviderName -eq 'Amazon Inc.' -or $_.ProviderName -eq 'Citrix Systems, Inc.' -or $_.ProviderName -like 'Intel*' -or $_.ProviderName -eq 'Amazon Web Services, Inc.') }
$pnp_drivers = Get-CimInstance -ClassName Win32_PnPEntity | Where-Object { $_.Service -eq 'xenvbd' -or `
$_.Manufacturer -like 'Intel*' -or $_.Manufacturer -eq 'Citrix Systems, Inc.' -or $_.Manufacturer -eq 'Amazon Inc.' -or $_.Manufacturer -eq 'Amazon Web Services, Inc.' }
foreach ($win_driver in $win_drivers) {
foreach ($pnp_driver in $pnp_drivers) {
if ($pnp_driver.Service -and $win_driver.OriginalFileName -like ("*{0}*" -f $pnp_driver.Service)) {
# Write the information to the Log Files
Write-Log ("# [Windows] Amazon EC2 Windows OS Driver Information : {0} v{1} " -f $pnp_driver.Name, $win_driver.Version)
}
}
}
} # end function Get-WindowsDriverInformation
function Get-WebContentToFile {
Param([String]$Uri, [String]$OutFile)
# Initialize Parameter
Set-Variable -Name FileAccessCheckStatus -Scope Script -Value ($Null)
Set-Variable -Name DownloadStatus -Scope Script -Value ($Null)
# Workaround -> https://github.com/PowerShell/PowerShell/issues/2138
Set-Variable -Name ProgressPreference -Scope Script -Value "SilentlyContinue"
# Test access to Internet resources
Try {
$FileAccessCheckStatus = Invoke-WebRequest -Uri $Uri -UseBasicParsing
if ($FileAccessCheckStatus.StatusCode -eq 200) {
Write-Log ("# [Get-WebContentToFile] URL is accessible : " + $Uri)
}
else {
Write-Log ("# [Get-WebContentToFile] (Error) URL is not accessible (file does not exist) : " + $Uri)
}
}
Catch {
Write-Log ("# [Get-WebContentToFile] (Error) Request response status is not normally terminated (status code is not 200) : " + $Uri)
}
# Download Internet Resources
if ( Test-Path $OutFile ) {
Write-Log ("# [Get-WebContentToFile] (Notice) File already exists : " + $OutFile)
Write-Log ("# [Get-WebContentToFile] (Notice) Do not download files from : " + $Uri)
}
else {
Write-Log ("# [Get-WebContentToFile] Download processing start [" + $Uri + "] -> [" + $OutFile + "]" )
Try {
$DownloadStatus = Measure-Command { (Invoke-WebRequest -Uri $Uri -UseBasicParsing -OutFile $OutFile) }
}
Catch {
Write-Log ("# [Get-WebContentToFile] (Error) URL is not accessible (file does not exist) : " + $Uri)
}
if ( Test-Path $OutFile ) {
Write-Log ("# [Get-WebContentToFile] Download processing time ( " + $DownloadStatus.TotalSeconds + " seconds )" )
Write-Log ("# [Get-WebContentToFile] Download processing complete [" + $Uri + "] -> [" + $OutFile + "]" )
}
}
} # end Get-WebContentToFile
function Get-WindowsServerInformation {
#--------------------------------------------------------------------------------------
# Windows Server OS Version Tables (Windows NT Version Tables)
# https://learn.microsoft.com/en-us/windows/win32/sysinfo/operating-system-version
#--------------------------------------------------------------------------------------
# - Windows Server 2003 : 5.2
# - Windows Server 2003 R2 : 5.2
# - Windows Server 2008 : 6.0
# - Windows Server 2008 R2 : 6.1
# - Windows Server 2012 : 6.2
# - Windows Server 2012 R2 : 6.3
# - Windows Server 2016 : 10.0 [Build No. 14393]
# - Windows Server 2019 : 10.0 [Build No. 17763]
# - Windows Server 2022 : 10.0 [Build No. 20348]
#--------------------------------------------------------------------------------------
# Initialize Parameter
Set-Variable -Name productName -Scope Script -Value ($Null)
Set-Variable -Name installOption -Scope Script -Value ($Null)
Set-Variable -Name osVersion -Scope Script -Value ($Null)
Set-Variable -Name osBuildLabEx -Scope Script -Value ($Null)
Set-Variable -Name osBuildNo -Scope Script -Value ($Null)
Set-Variable -Name windowInfoKey -Option Constant -Scope Local -Value "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion"
Set-Variable -Name fullServer -Option Constant -Scope Local -Value "Full"
Set-Variable -Name nanoServer -Option Constant -Scope Local -Value "Nano"
Set-Variable -Name serverCore -Option Constant -Scope Local -Value "Server Core"
Set-Variable -Name serverOptions -Option Constant -Scope Local -Value @{ 0 = "Undefined"; 12 = $serverCore; 13 = $serverCore;
14 = $serverCore; 29 = $serverCore; 39 = $serverCore; 40 = $serverCore; 41 = $serverCore; 43 = $serverCore;
44 = $serverCore; 45 = $serverCore; 46 = $serverCore; 63 = $serverCore; 143 = $nanoServer; 144 = $nanoServer;
147 = $serverCore; 148 = $serverCore;
}
# Get ProductName and BuildLabEx from HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion
if (Test-Path $windowInfoKey) {
$windowInfo = Get-ItemProperty -Path $windowInfoKey
$productName = $windowInfo.ProductName
$osBuildLabEx = $windowInfo.BuildLabEx
if ($windowInfo.CurrentMajorVersionNumber -and $windowInfo.CurrentMinorVersionNumber) {
$osVersion = ("{0}.{1}" -f $windowInfo.CurrentMajorVersionNumber, $windowInfo.CurrentMinorVersionNumber)
}
}
# Get Version and SKU from Win32_OperatingSystem
$osInfo = Get-CimInstance Win32_OperatingSystem | Select-Object Version, BuildNumber, OperatingSystemSKU
$osBuildNumber = [int]$osInfo.BuildNumber
$osSkuNumber = [int]$osInfo.OperatingSystemSKU
if (-not $osVersion -and $osInfo.Version) {
$osVersionSplit = $osInfo.Version.Split(".")
if ($osVersionSplit.Count -gt 1) {
$osVersion = ("{0}.{1}" -f $osVersionSplit[0], $osVersionSplit[1])
}
elseif ($osVersionSplit.Count -eq 1) {
$osVersion = ("{0}.0" -f $osVersionSplit[0])
}
}
if ($serverOptions[$osSkuNumber]) {
$installOption = $serverOptions[$osSkuNumber]
}
else {
$installOption = $fullServer
}
# Identify the version of Windows Server 2016, 2019, 2022
#---------------------------------------------------------------------------
# - Windows Server 2016 : 10.0 [Build No. 14393]
# - Windows Server 2019 : 10.0 [Build No. 17763]
# - Windows Server 2022 : 10.0 [Build No. 20348]
#---------------------------------------------------------------------------
# Set Parameter
if ($osBuildNumber -eq "14393") {
Set-Variable -Name WindowsOSName -Option Constant -Scope Script -Value "Windows Server 2016"
}
elseif ($osBuildNumber -eq "17763") {
Set-Variable -Name WindowsOSName -Option Constant -Scope Script -Value "Windows Server 2019"
}
elseif ($osBuildNumber -eq "20348") {
Set-Variable -Name WindowsOSName -Option Constant -Scope Script -Value "Windows Server 2022"
}
else {
Set-Variable -Name WindowsOSName -Option Constant -Scope Script -Value ($productName)
}
# Write the information to the Log Files
Write-Log ("# [Windows] Windows Server OS Product Name : {0}" -f $productName)
Write-Log ("# [Windows] Windows Server OS Name : {0}" -f $WindowsOSName)
Write-Log ("# [Windows] Windows Server OS Version : {0}" -f $osVersion)
Write-Log ("# [Windows] Windows Server OS Install Option : {0}" -f $installOption)
Write-Log ("# [Windows] Windows Server Build Number : {0}" -f $osBuildNumber)
Write-Log ("# [Windows] Windows Server Build Lab Ex : {0}" -f $osBuildLabEx)
Write-Log ("# [Windows] Windows Server OS Language : {0}" -f ([CultureInfo]::CurrentCulture).IetfLanguageTag)
Write-Log ("# [Windows] Windows Server OS TimeZone : {0}" -f ([TimeZoneInfo]::Local).StandardName)
Write-Log ("# [Windows] Windows Server OS Offset : {0}" -f ([TimeZoneInfo]::Local).GetUtcOffset([DateTime]::Now))
# Set Parameter
Set-Variable -Name WindowsOSVersion -Option Constant -Scope Script -Value ($osVersion.ToString())
Set-Variable -Name WindowsOSLanguage -Option Constant -Scope Script -Value (([CultureInfo]::CurrentCulture).IetfLanguageTag)
} # end function Get-WindowsServerInformation
########################################################################################################################
#
# Windows Bootstrap Individual requirement function
# [Dependent on function]
# - Write-Log
# - Get-CustomizeEc2InstanceMetadata
# - Get-Ec2LaunchV2Version
# - Get-Ec2LaunchVersion
# - Get-Ec2ConfigVersion
# - Get-WindowsServerInformation
#
########################################################################################################################
function Get-Ec2BootstrapProgram {
# Checking the existence of the sysprep file
Write-Log "# [Windows - OS Settings] Checking the existence of the sysprep file"
if (Test-Path $EC2Launchv2SysprepFile) {
Set-Variable -Name SysprepFile -Value $EC2Launchv2SysprepFile
Write-Log ("# [Windows - OS Settings] Found sysprep file [EC2Launch v2] : " + $SysprepFile)
if ($WindowsOSVersion -match "^6.*|^10.*") {
Get-Ec2LaunchV2Version
}
}
elseif (Test-Path $EC2LaunchSysprepFile) {
Set-Variable -Name SysprepFile -Value $EC2LaunchSysprepFile
Write-Log ("# [Windows - OS Settings] Found sysprep file [EC2Launch] : " + $SysprepFile)
if ($WindowsOSVersion -match "^10.*") {
Get-Ec2LaunchVersion
}
}
elseif (Test-Path $EC2ConfigSysprepFile) {
Set-Variable -Name SysprepFile -Value $EC2ConfigSysprepFile
Write-Log ("# [Windows - OS Settings] Found sysprep file [EC2Config] : " + $SysprepFile)
if ($WindowsOSVersion -match "^5.*|^6.*") {
Get-Ec2ConfigVersion
}
}
else {
Write-Log "# [Warning] Not Found - Sysprep files"
}
} # end function Update-SysprepAnswerFile
function Update-SysprepAnswerFile($SysprepAnswerFile) {
[xml]$SysprepXMLDocument = Get-Content -Path $SysprepAnswerFile -Encoding UTF8
$SysprepNamespace = New-Object System.Xml.XmlNamespaceManager($SysprepXMLDocument.NameTable)
$SysprepNamespace.AddNamespace("u", $SysprepXMLDocument.DocumentElement.NamespaceURI)
$SysprepSettings = $SysprepXMLDocument.SelectSingleNode("//u:settings[@pass='oobeSystem']", $SysprepNamespace)
$Sysprep_Node_International = $SysprepSettings.SelectSingleNode("u:component[@name='Microsoft-Windows-International-Core']", $SysprepNamespace)
$Sysprep_Node_Shell = $SysprepSettings.SelectSingleNode("u:component[@name='Microsoft-Windows-Shell-Setup']", $SysprepNamespace)
$Sysprep_Node_International.SystemLocale = "ja-JP"
$Sysprep_Node_International.UserLocale = "ja-JP"
$Sysprep_Node_Shell.TimeZone = "Tokyo Standard Time"
$SysprepXMLDocument.Save($SysprepAnswerFile)
} # end function Get-Ec2BootstrapProgram
########################################################################################################################
#
# Start of script
#
########################################################################################################################
#-----------------------------------------------------------------------------------------------------------------------
# Timezone Setting
#-----------------------------------------------------------------------------------------------------------------------
#Get OS Information & Language
$Local:TimezoneLanguage = ([CultureInfo]::CurrentCulture).IetfLanguageTag
if ($TimezoneLanguage -eq "ja-JP") {
if (Get-Command -CommandType Cmdlet | Where-Object { $_.Name -eq "Set-TimeZone" }) {
# Set Initialize Parameter
Set-Variable -Name TimeZoneInformation -Scope Script -Value ($Null)
# Get TimeZone
$TimeZoneInformation = (Get-TimeZone | Select-Object Id, Displayname, StandardName, BaseUtcOffset)
Write-Log ("# [Windows - OS Settings] TimeZone - [Id - {0}] [Displayname - {1}] [StandardName - {2}] [BaseUtcOffset - {3}]" -f $TimeZoneInformation.Id, $TimeZoneInformation.Displayname, $TimeZoneInformation.StandardName, $TimeZoneInformation.BaseUtcOffset)
Set-TimeZone -Id "Tokyo Standard Time" | Out-Null
Start-Sleep -Seconds 5
# Get TimeZone
$TimeZoneInformation = (Get-TimeZone | Select-Object Id, Displayname, StandardName, BaseUtcOffset)
Write-Log ("# [Windows - OS Settings] TimeZone - [Id - {0}] [Displayname - {1}] [StandardName - {2}] [BaseUtcOffset - {3}]" -f $TimeZoneInformation.Id, $TimeZoneInformation.Displayname, $TimeZoneInformation.StandardName, $TimeZoneInformation.BaseUtcOffset)
}
else {
Get-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\TimeZoneInformation"
Set-TimeZoneCompatible "Tokyo Standard Time"
Start-Sleep -Seconds 5
Get-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\TimeZoneInformation"
}
}