-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWinPostInstall.ps1
More file actions
5439 lines (4403 loc) · 213 KB
/
WinPostInstall.ps1
File metadata and controls
5439 lines (4403 loc) · 213 KB
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
# ===============================
# WinPostInstall
# ===============================
<#
.SYNOPSIS
WinPostInstall automates the configuration, customization, and hardening of Windows systems post-installation.
.DESCRIPTION
WinPostInstall is a modular and idempotent PowerShell script crafted to transform a freshly installed Windows system into a hardened, decluttered, and operational environment.
It encapsulates system configuration, privacy and telemetry reduction, curated software provisioning (via Winget, Microsoft Store, or local binaries), security enhancements (Defender, WDAC, services, firewall), interface theming, and the removal of superfluous components.
Tailored for developers, system administrators, and security professionals, it offers precision, consistency, and autonomy — all in a single pass.
.INPUTS
None. All logic is internal or prompted contextually.
.OUTPUTS
Structured terminal output with styled status indicators. Optional logs may be generated.
.REQUIREMENTS
- PowerShell 5.1 or higher
- Administrator privileges
- Internet access (for package retrieval)
.LICENSE
GNU Affero General Public License v3.0
https://github.com/franckferman/franckferman/blob/stable/LICENSE
.CREDITS
With inspiration from:
- HardeningKitty — https://github.com/scipag/HardeningKitty
- Win11Debloat — https://github.com/Raphire/Win11Debloat
- Harden-Windows-Security — https://github.com/HotCakeX/Harden-Windows-Security
.EXAMPLE
PS C:\> Set-ExecutionPolicy Bypass -Scope Process -Force; .\WinPostInstall.ps1
.NOTES
Author : Franck FERMAN
Version : 1.0.0
License : GNU AGPLv3
GitHub : https://github.com/franckferman/
.LINK
https://github.com/franckferman/WinPostInstall
#>
[CmdletBinding()]
param(
[Parameter(HelpMessage="Display usage information and exit.")]
[switch]$Help,
[Parameter(HelpMessage="Execute post-reboot logic (used after system restart).")]
[switch]$AfterRestart
)
function Get-Banner {
[CmdletBinding()]
param(
[Parameter(Mandatory = $false, HelpMessage = "The banner name or banner group to retrieve.")]
[string]$BannerType
)
<#
.SYNOPSIS
Retrieves an ASCII banner by name or from a group of themed banners.
.DESCRIPTION
Returns a predefined ASCII banner based on the given name or category.
If no name is specified, a random banner is returned.
.PARAMETER BannerType
Optional. The name of the banner to retrieve, or a group name (e.g., 'Space_Banners').
If omitted, a random banner from all available ones will be returned.
.OUTPUTS
[string] — An ASCII banner string.
.EXAMPLE
Get-Banner -BannerType "Window_PS_Terminal"
.EXAMPLE
Get-Banner -BannerType "Space_Banners"
#>
$Banners = @{
"Window_PS_Terminal" = @"
_______________________________________________________________________
|[>] Win-Post-Install [-]|[]|[x]"| |
|"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""|"|
|PS C:\WINDOWS\system32> Set-Location -Path C:\Users\$env:USERNAME | |
|PS C:\Users\$env:USERNAME> .\WinPostInstall.ps1 | |
| |_|
|_____________________________________________________________________|/|
"@
"Window_PS_Terminal_Old_Computer" = @"
.--------.
|.------.|
||PS > ||
|| ||
|'------'|
.-^--------^-.
| ---~[WPI ] |
| [Franck]---~|
'------------'
"@
"Monkey" = @"
.="=.
_/.-.-.\_ _
( ( o o ) ) ))
.-------. |/ " \| //
| -WPI- | \'---'/ //
_| _GIT_ |_ /'"""'\ ((
=(_|_____|_)= / /_,_\ \ \\
|:::::::::| \_\\_'__/ \ ))
|:::::::[]| /' /'~\ |//
|o=======.| / / \ /
'"""""""""' ,--',--'\/\
'--' '--'
"@
"Windows_logo" = @"
.----------------.
| _ |
| _.-'|'-._ |
| .__.| | | |
| |_.-'|'-._| |
| '--'| | | |
| '--'|_.-' '-._| |
WPI| '--' |
'----------------'
"@
"Windows_on_laptop" = @"
._________________.
|.---------------.|
|| --._ .-. ||
|| --._| | | ||
|| --._|"|"| ||
|| --._|.-.| ||
||_______________||
/.-.-.-.-.-.-.-.-.\
/.-.-.-.-.-.-.-.-.-.\
/.-.-.-.-.-.-.-.-.-.-.\
/______/__________\___o_\
\_______________________/
"@
"Rocket_launch" = @"
* * * *
* *
* * ___
* * | | |
* _________## * / \ | |
@\\\\\\\\\## * | |--o|===|-|
* @@@\\\\\\\\##\ \|/|/ |---| |g|
@@ @@\\\\\\\\\\\ \|\\|//|/ * / \ |i|
* @@@@@@@\\\\\\\\\\\ \|\|/|/ | W | |t|
@@@@@@@@@----------| \\|// | P |=| |
__ @@ @@@ @@__________| \|/ | I | | |
____|_@|_ @@@@@@@@@__________| \|/ |_______| |_|
=|__ _____ |= @@@@ .@@@__________| | |@| |@| | |
____0_____0__\|/__@@@@__@@@__________|_\|/__|___\|/__\|/___________|_|_
"@
"Space_odyssey" = @"
WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW
W \ :: / W
W \ ______________ / W i n W
W \ _____/ ____________ \_____ / P o s t W
W \ __/ _____/ :: \_____ \__ / I n s t a l l W
W __/ __/ :: \__ \__ W
W _/ __/ ,--. :: ,----- _ \__ \_ -=[ franck ]=- W
W _/ _/ \ ( ) :: (_) ( ) / \_ \_ (ferman) W
W _/ _/ \ o) (_ :: ----' / \_ \_ W
W / _/ \ :: / \_ \ W
W / / \ ____________ / \ \ W
W / / ._._._ \ ____/ :: \____ / .___, \ \ W
W / / | | | ) _/ :: \_ | | \ \ W
W / / | | |/ _/ \ :: / \_ _|_|_ \ \ W
W | | | _/ \ :: / \_ | | W
W | | / \ :: / \ _ _ | | W
W / / __ / \ 00000000 / \ \ / \ \ W
W | | ._( )_, | 000########000 | X | | W
W | | ------ | 00##############00 | (_) | | W
W | | | 0##################0 | | | W
W:| |::::::::::|:::::::::0#####-( WPI )-####0:::::::::|::::::::::| |:::::::::W
W | | | 0##################0 | _ _ | | W
W | | _,_, | 00##############00 | \ / | | W
W \ \ | | | \ /000########000\ / | / / W
W | | | | |/ \ / 00000000 \ / | | | W
W | | \_ / :: .. \ _/ __________ W
W \ \ __, \_ / :: \\_) \ _/ \________/ W
W \ \ ,'| \_ :: \\_ _/ |-o o-|| W
W \ \ o' / \____ :: \ '-._ ) j ( | _ W
W \ \ ' / \__________/ '. '-.__.----||=|| '--'/-, W
W \ \_ / :: '. \---|||||-----' /-. W
W \_ \_ / _____ :: _ '._ ) .: O-:._,|._( '. W
W \_ \_ / | _,-' :: \_/_\___/ '----/ || || '|' _\-, ) W
W \_ \__ (__) :: \_/ \___/ ___| || || _|3=.___,' W
W \__ \__ :: __/ __| || || '-' | W
W / \__ \_____ :: _____/ __/ | || || | W
W / \_____ \__________/ _____/ | || || | W
W / \____________/ | || || | W
W / :: | || || | W
W / :: | || || | W
W / :: | || || | W
W / :: | || || | W
W / :: | || || | W
W / :: | || || | W
W / _____________________________ || | W
W / _______,--------------'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%'--------------.__W
W ,--'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%W
W.'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%W
W%%%%%[ franckferman/Win-PostInstall ]%%%%%%%%%%%%%%%%%%%%%%W
WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW
"@
"Galaxy" = @"
. . . . . . . . . . .
. . . . . . .
. . . . . . . . .
. . . _......____._ . .
. . . ..--'"" . """"""---... .
_...--"" ................ '-. .
.-' ...:'::::;:::%:.::::::_;;:... '-.
.-' ..::::''''' _...---'"""":::+;_::. '. .
. .' . ..::::' _.-"" :::)::. '.
. ..;:::' _.-' . f::':: o '_
/ .:::%' . .-" .-. ::;;:. '
. .' ""::.::' .-" _.--'"""-. ( ) ::.:: '
.' ::;:' .' .-" .d@@b. \ . . '-' ::%:: ' .
.' :,::' / . (' 8@@@@8 j .-' ::::: " o
| . :.%:' . | ( '@@@P' .' .-" ::.:: . '
| :::: ( -..____...-' .-" .::::' /
. | ':':: '. ..--' . .::':: . /
j '::::: '-._____...---"" .::%:::' .' .
\ ::.:%.. . . ...:,::::' .'
. \ ':::':.. ....::::.::::' .-' .
\ . '':::%::'::.......:::::%::.::::'' .-'
. '. . ''::::::%::::.::;;:::::''' _.-' .
. '-.. . . ''''''''' . _.-' . .
. ""--...____ . ______......--' . . .
. . . """""""" . . . . .
. . . . . . . . .
. . . . . . . . . . .
"@
}
$BannerGroups = @{
"Window_Banners" = @("Window_PS_Terminal", "Window_PS_Terminal_Old_Computer")
"Windows_Banners" = @("Windows_logo", "Windows_on_laptop")
"Space_Banners" = @("Rocket_launch", "Space_odyssey", "Galaxy")
"Misc_Banners" = @("Monkey", "Teddy_Screen")
}
if ($BannerGroups.ContainsKey($BannerType)) {
$selected = Get-Random -InputObject $BannerGroups[$BannerType]
return $Banners[$selected]
}
if (-not $BannerType) {
$selected = Get-Random -InputObject $Banners.Keys
return $Banners[$selected]
}
return $Banners[$BannerType]
}
function Show-Banner {
[CmdletBinding()]
param (
[Parameter(Mandatory = $false, HelpMessage = "Banner name or banner group (e.g. 'Window_Banners').")]
[string]$BannerType,
[Parameter(Mandatory = $false, HelpMessage = "Foreground color for the banner.")]
[ValidateSet("Black", "DarkBlue", "DarkGreen", "DarkCyan", "DarkRed", "DarkMagenta", "DarkYellow", "Gray", "DarkGray", "Blue", "Green", "Cyan", "Red", "Magenta", "Yellow", "White")]
[string]$ForegroundColor = "Cyan"
)
<#
.SYNOPSIS
Displays an ASCII banner by name or group, with customizable color.
.DESCRIPTION
Retrieves and prints an ASCII banner to the console. The banner can be selected by name or from a group (e.g., "Window_Banners").
If no name is provided, a random banner is displayed.
Color customization is supported through the ForegroundColor parameter.
.PARAMETER BannerType
The name of the banner or banner group to display. If omitted, a random one is selected.
.PARAMETER ForegroundColor
The color used to render the banner. Defaults to Cyan. Accepts any standard console color.
.OUTPUTS
[string] — The ASCII banner rendered to the console.
.EXAMPLE
Show-Banner -BannerType "Monkey" -ForegroundColor Magenta
.EXAMPLE
Show-Banner -BannerType "Space_Banners"
.EXAMPLE
Show-Banner
Displays a random banner in Cyan.
#>
if (-not $BannerType) {
$allBannerKeys = @(
"Window_PS_Terminal",
"Window_PS_Terminal_Old_Computer",
"Teddy_Screen",
"Monkey",
"Windows_logo",
"Windows_on_laptop",
"Rocket_launch",
"Space_odyssey",
"Galaxy"
)
$BannerType = Get-Random -InputObject $allBannerKeys
}
$banner = Get-Banner -BannerType $BannerType
if ($null -ne $banner) {
Write-Host $banner -ForegroundColor $ForegroundColor
}
else {
Write-Warning "❌ Banner '$BannerType' not found."
}
}
function Get-SystemInfoData {
[CmdletBinding()]
param()
<#
.SYNOPSIS
Retrieves basic system identity information.
.DESCRIPTION
Returns a structured object containing:
- The current timestamp (localized)
- The system's hostname
- The domain name (or 'WORKGROUP' if not domain-joined)
.OUTPUTS
[PSCustomObject] with the following properties:
- Timestamp [string]
- Hostname [string]
- Domain [string]
.EXAMPLE
Get-SystemInfoData
#>
$sysInfo = Get-CimInstance -ClassName Win32_ComputerSystem
return [PSCustomObject]@{
Timestamp = (Get-Date).ToString('yyyy-MM-dd HH:mm:ss')
Hostname = $env:COMPUTERNAME
Domain = if ($sysInfo.PartOfDomain) { $sysInfo.Domain } else { 'WORKGROUP' }
}
}
function Pause-ForUser {
[CmdletBinding()]
param (
[Parameter(Mandatory = $false)]
[string]$Message = "Press Enter to continue...",
[Parameter(Mandatory = $false)]
[bool]$IncludeFun = $true,
[Parameter(Mandatory = $false)]
[switch]$Quiet
)
<#
.SYNOPSIS
Pauses script execution until the user presses Enter.
.DESCRIPTION
Displays a prompt message and optionally a humorous security-related message before waiting for user confirmation.
.PARAMETER Message
The message shown before pausing. Defaults to: "Press Enter to continue...".
.PARAMETER IncludeFun
If set, displays a fun or sarcastic message chosen randomly from a curated set. Enabled by default.
.PARAMETER Quiet
If set, suppresses all output. The script will still wait, but display nothing.
.EXAMPLE
Pause-ForUser
Pauses with default prompt and random fun message.
.EXAMPLE
Pause-ForUser -Message "Ready for phase 2?" -IncludeFun:$false
.EXAMPLE
Pause-ForUser -Quiet
#>
if (-not $Quiet) {
if ($IncludeFun) {
$messages = @(
"[🧠] Think before you continue, $env:USERNAME.",
"[🧠] Think before you continue, $env:USERNAME.",
"[🧠] Think before you continue, $env:USERNAME.",
"[💤] Waiting... like Windows Update before it crashes.",
"[💤] Waiting... like Windows Update before it crashes.",
"[🚀] Hang tight, astronaut. We’re almost there."
)
# $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
# Write-Host "`n[👽] $timestamp — Confirm transmission before proceeding..." -ForegroundColor Green
Write-Host ($messages | Get-Random) -ForegroundColor DarkYellow
}
Write-Host "`n$Message" -ForegroundColor Gray
}
[void][System.Console]::ReadLine()
}
function ScriptExit {
[CmdletBinding()]
param (
[Parameter(Position = 0)]
[int]$ExitCode = 0,
[Parameter(Position = 1)]
[string]$ExitMessage,
[Parameter()]
[switch]$NoExitMessage
)
<#
.SYNOPSIS
Terminates the script execution with a specified exit code.
.DESCRIPTION
Provides a centralized and clean exit mechanism. Outputs a message (custom or default) unless -NoExitMessage is used.
.PARAMETER ExitCode
Exit code to return. Default is 0 (success).
.PARAMETER ExitMessage
Optional. Message to display before exiting. If omitted, a generic message is shown.
.PARAMETER NoExitMessage
If set, suppresses any output before termination.
.EXAMPLE
ScriptExit -ExitCode 1 -ExitMessage "Fatal error during execution."
.EXAMPLE
ScriptExit
Exits with code 0 and default message.
.EXAMPLE
ScriptExit -ExitCode 2 -NoExitMessage
Exits silently with code 2.
#>
if (-not $NoExitMessage) {
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
if (-not $ExitMessage) {
$ExitMessage = "Script terminated with exit code $ExitCode."
}
$prefix = "[👽] $timestamp —"
if ($ExitCode -eq 0) {
Write-Host "$prefix $ExitMessage" -ForegroundColor Green
} else {
Write-Host "$prefix $ExitMessage" -ForegroundColor Red
}
}
exit $ExitCode
}
function Display-Help {
[CmdletBinding()]
param()
<#
.SYNOPSIS
Displays the help menu for WinPostInstall.
.DESCRIPTION
Prints a detailed guide covering features, usage, and parameters of the WinPostInstall script.
Ideal for users who want an overview of capabilities, prerequisites, and usage examples.
.EXAMPLE
PS > .\WinPostInstall.ps1 -Help
.LINK
https://github.com/franckferman/WinPostInstall
#>
# $helpText = Get-Content .\Help.txt -Encoding UTF8
$helpText = @"
┌──────────────────────────────────────────────────────────────┐
│ 🛸 WinPostInstall – Help Menu │
└──────────────────────────────────────────────────────────────┘
DESCRIPTION:
WinPostInstall automates the configuration, customization,
and hardening of Windows systems post-installation.
WinPostInstall is a modular and idempotent PowerShell script crafted to transform a freshly installed Windows system
into a hardened, decluttered, and operational environment.
It encapsulates system configuration, privacy and telemetry reduction, curated software provisioning (via Winget, Microsoft Store, or local binaries),
security enhancements (Defender, WDAC, services, firewall), interface theming, and the removal of superfluous components.
Tailored for developers, system administrators, and security professionals, it offers precision, consistency, and autonomy — all in a single pass.
USAGE:
Open an elevated PowerShell (<=5.1) prompt and run:
PS> Set-ExecutionPolicy Bypass -Scope Process
PS> .\WinPostInstall.ps1
PARAMETERS:
-Help Show this help screen.
-AfterRestart Continue the setup after reboot (post-stage).
-Debug Enable verbose output for troubleshooting.
REQUIREMENTS:
- PowerShell 5.1 or later
- Admin rights
- Internet access for package installation
CREDITS:
- HardeningKitty – https://github.com/scipag/HardeningKitty
- Win11Debloat – https://github.com/Raphire/Win11Debloat
- Harden-Windows-Security – https://github.com/HotCakeX/Harden-Windows-Security
SOURCE:
https://github.com/franckferman/WinPostInstall
AUTHOR:
Franck FERMAN – contact@franckferman.fr
──────────────────────────────────────────────────────────────
"@
Write-Host ''
Write-Host $helpText -ForegroundColor Cyan
Write-Host ''
ScriptExit -NoExitMessage
}
function Test-AdminRights {
[CmdletBinding()]
[OutputType([bool])]
param()
<#
.SYNOPSIS
Checks whether the current user has administrative privileges.
.DESCRIPTION
Determines if the current session is elevated by evaluating whether the current user
belongs to the local Administrators group using .NET security principals.
.OUTPUTS
[bool] — $true if the user has admin rights; otherwise, $false.
.EXAMPLE
if (Test-AdminRights) {
Write-Host "You are running as an administrator."
} else {
Write-Host "You are not running as an administrator."
}
#>
$identity = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$principal = New-Object System.Security.Principal.WindowsPrincipal($identity)
$adminRole = [System.Security.Principal.WindowsBuiltInRole]::Administrator
return $principal.IsInRole($adminRole)
}
function Get-WANStatus {
[CmdletBinding()]
[OutputType([string])]
param (
[Parameter(Mandatory = $false, HelpMessage = "List of URLs to test. One will be selected at random.")]
[System.Uri[]]$urls = @(
'https://httpbin.org/get',
'https://httpstat.us/200',
'https://1.1.1.1'
)
)
<#
.SYNOPSIS
Tests external WAN connectivity by querying a random URL.
.DESCRIPTION
Selects a random URL from the provided list (or defaults) and sends an HTTP GET request.
If a valid response is received (HTTP 200), returns "Online". Otherwise, returns "Offline"
with error or status details.
.PARAMETER urls
Optional. An array of URLs to test connectivity. Defaults to known HTTP test endpoints.
.OUTPUTS
[string] — Returns "Online", or "Offline - <reason>".
.EXAMPLE
Get-WANStatus -urls 'https://httpbin.org/get'
.EXAMPLE
Get-WANStatus
#>
$selectedUrl = Get-Random -InputObject $urls
$ProgressPreference = 'SilentlyContinue'
try {
$response = Invoke-WebRequest -Uri $selectedUrl -UseBasicParsing -TimeoutSec 5 -Headers @{
'User-Agent' = 'WinPostInstall/1.0.0'
}
if ($response.StatusCode -eq 200) {
return "Online"
} else {
return "Offline – Received status code $($response.StatusCode)"
}
} catch {
return "Offline – Error: $($_.Exception.Message)"
}
}
function Get-FirewallEnabledStatus {
[CmdletBinding()]
[OutputType([PSCustomObject[]])]
param (
[Parameter(Mandatory = $false)]
[ValidateSet("Domain", "Private", "Public")]
[string[]]$Profiles = @("Domain", "Private", "Public")
)
<#
.SYNOPSIS
Retrieves the Windows Firewall "Enabled" status for specified profiles.
.DESCRIPTION
Returns an array of structured objects indicating whether Windows Defender Firewall is enabled
for each of the selected profiles: Domain, Private, or Public.
.PARAMETER Profiles
Optional. One or more profile names to check. Valid values: Domain, Private, Public.
Defaults to all three profiles.
.OUTPUTS
[PSCustomObject[]] — Each object contains:
- Profile [string]
- Enabled [bool]
.EXAMPLE
Get-FirewallEnabledStatus
.EXAMPLE
Get-FirewallEnabledStatus -Profiles "Private", "Public"
#>
foreach ($profile in $Profiles) {
$fw = Get-NetFirewallProfile -Profile $profile
[PSCustomObject]@{
Profile = $profile
Enabled = [bool]$fw.Enabled
}
}
}
function Get-FirewallProfileState {
[CmdletBinding()]
[OutputType([PSCustomObject[]])]
param (
[Parameter(Mandatory = $false)]
[ValidateSet("Domain", "Private", "Public")]
[string[]]$Profiles = @("Domain", "Private", "Public")
)
<#
.SYNOPSIS
Retrieves the full Windows Firewall configuration state for specified profiles.
.DESCRIPTION
Returns an array of structured objects for each specified Windows Firewall profile.
Each object includes the enabled state, default inbound/outbound actions, and whether inbound/local rules are allowed.
.PARAMETER Profiles
Optional. List of profiles to query. Valid values: Domain, Private, Public.
Defaults to all three.
.OUTPUTS
[PSCustomObject[]] — Each object includes:
- Profile [string]
- Enabled [bool]
- DefaultInboundAction [string]
- DefaultOutboundAction [string]
- AllowInboundRules [bool]
- AllowLocalFirewallRules [bool]
.EXAMPLE
Get-FirewallProfileState
.EXAMPLE
Get-FirewallProfileState -Profiles "Private", "Public"
#>
foreach ($profile in $Profiles) {
$fw = Get-NetFirewallProfile -Profile $profile
[PSCustomObject]@{
Profile = $profile
Enabled = [bool]$fw.Enabled
DefaultInboundAction = $fw.DefaultInboundAction
DefaultOutboundAction = $fw.DefaultOutboundAction
AllowInboundRules = [bool]$fw.AllowInboundRules
AllowLocalFirewallRules = [bool]$fw.AllowLocalFirewallRules
}
}
}
function Apply-FirewallHardening {
[CmdletBinding(SupportsShouldProcess)]
param (
[Parameter(ValueFromPipeline = $true)]
[ValidateSet("Domain", "Private", "Public")]
[string[]]$Profiles = @("Domain", "Private", "Public")
)
<#
.SYNOPSIS
Applies firewall hardening settings to the specified profiles.
.DESCRIPTION
Silently enforces strict Windows Firewall configurations per profile.
Each targeted profile will be configured as follows:
- Firewall enabled
- DefaultInboundAction: Block
- DefaultOutboundAction: Allow
- Inbound rules (global & local): blocked
This function performs silent remediation and is designed to be invoked
by higher-level functions that handle display, logging, or user feedback.
.PARAMETER Profiles
Optional. List of firewall profiles to harden. Valid values: Domain, Private, Public.
Defaults to all three.
.INPUTS
[string[]] — Accepts profile names via pipeline or parameter.
.OUTPUTS
None.
.EXAMPLE
Apply-FirewallHardening
.EXAMPLE
Apply-FirewallHardening -Profiles "Private", "Public"
#>
foreach ($profile in $Profiles) {
$fw = Get-NetFirewallProfile -Profile $profile
if (-not $fw.Enabled) {
Set-NetFirewallProfile -Profile $profile -Enabled True
}
if ($fw.DefaultInboundAction -ne "Block") {
Set-NetFirewallProfile -Profile $profile -DefaultInboundAction Block
}
if ($fw.DefaultOutboundAction -ne "Allow") {
Set-NetFirewallProfile -Profile $profile -DefaultOutboundAction Allow
}
if ($fw.AllowInboundRules -or $fw.AllowLocalFirewallRules) {
Set-NetFirewallProfile -Profile $profile `
-AllowInboundRules $false `
-AllowLocalFirewallRules $false
}
}
}
function Show-FirewallProfileState {
[CmdletBinding()]
param(
[Parameter(Mandatory = $true, ValueFromPipeline = $true)]
[ValidateNotNullOrEmpty()]
$State
)
<#
.SYNOPSIS
Displays the state of each Windows Firewall profile in a formatted table.
.DESCRIPTION
Takes an array of objects (as returned by Get-FirewallProfileState) and displays a
timestamped, color-coded table summarizing the status of each firewall profile.
.PARAMETER State
The state object returned by Get-FirewallProfileState. Must contain the properties:
Profile, Enabled, DefaultInboundAction, DefaultOutboundAction, AllowInboundRules, AllowLocalFirewallRules.
.OUTPUTS
None. Writes styled output to the console.
.EXAMPLE
$state = Get-FirewallProfileState
Show-FirewallProfileState -State $state
#>
$ts = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
Write-Host "`n[👽] $ts - Current Windows Firewall Profile Status" -ForegroundColor Cyan
$State | Format-Table Profile, Enabled, DefaultInboundAction, DefaultOutboundAction, AllowInboundRules, AllowLocalFirewallRules -AutoSize
}
function Harden-AllFirewallProfiles {
[CmdletBinding()]
[OutputType([PSCustomObject])]
param()
<#
.SYNOPSIS
Executes a full firewall hardening workflow across all standard profiles.
.DESCRIPTION
This function:
1. Retrieves the current firewall configuration for Domain, Private, and Public profiles.
2. Applies strict hardening rules to each profile.
3. Retrieves the updated state after hardening.
Returns a structured object containing the initial and final states.
All console output should be handled externally by display functions such as Show-FirewallProfileState.
.OUTPUTS
[PSCustomObject] — Contains:
- Initial [PSCustomObject[]] : Pre-hardening state
- Final [PSCustomObject[]] : Post-hardening state
.EXAMPLE
$result = Harden-AllFirewallProfiles
Show-FirewallProfileState -State $result.Final
#>
$profiles = @("Domain", "Private", "Public")
$initialState = Get-FirewallProfileState -Profiles $profiles
Apply-FirewallHardening -Profiles $profiles
$finalState = Get-FirewallProfileState -Profiles $profiles
return [PSCustomObject]@{
Initial = $initialState
Final = $finalState
}
}
function Invoke-FirewallHardening {
[CmdletBinding()]
param()
<#
.SYNOPSIS
Runs the full Windows Firewall hardening routine with interactive output.
.DESCRIPTION
Orchestrates the complete hardening flow:
- Displays initial status
- Applies hardened firewall configuration
- Shows final state
This function handles all user-facing output and timestamps,
and is designed as the UX entry point for firewall security.
.OUTPUTS
None. Writes styled output to the console.
.EXAMPLE
Invoke-FirewallHardening
#>
$tsStart = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
Write-Host "[👽] $tsStart - Auditing current Windows Firewall state..." -ForegroundColor Cyan
$results = Harden-AllFirewallProfiles
Write-Host "`n[📋] BEFORE:" -ForegroundColor DarkGray
Show-FirewallProfileState -State $results.Initial
Write-Host "[🛡️] AFTER:" -ForegroundColor DarkGreen
Show-FirewallProfileState -State $results.Final
$tsEnd = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
Write-Host "[👽] $tsEnd - Firewall hardening routine completed." -ForegroundColor Cyan
}
function Harden-FirewallAndShowStatus {
[CmdletBinding()]
param()
<#
.SYNOPSIS
Convenience wrapper to run full firewall hardening with stylish UX and sarcasm.
.DESCRIPTION
Prints a start banner, invokes the full hardening sequence (audit → apply → show),
and finishes with a timestamped log + random sarcastic security quote.
This function is intended as the final step for firewall hardening in WinPostInstall.
.OUTPUTS
None. Writes all output to the console.
.EXAMPLE
Harden-FirewallAndShowStatus
#>
$tsStart = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
Write-Host "[👽] $tsStart - Starting firewall hardening..." -ForegroundColor Cyan
Write-Host ""
Invoke-FirewallHardening
$messages = @(
"[🛡️] ...We sealed those open ports, but the NSA has a master key — allegedly.",
"[🛡️] ...We sealed those open ports, but the NSA has a master key — allegedly.",
"[🛡️] ...We sealed those open ports, but the NSA has a master key — allegedly.",
"[👽] ...We locked the front door. Just remember: Windows is named after windows.",
"[👽] ...We locked the front door. Just remember: Windows is named after windows.",
"[👽] ...We locked the front door. Just remember: Windows is named after windows.",
"[🧬] DefaultInboundAction set to Block. But Defender let Excel spawn PowerShell with -nop -w hidden anyway.",
"[🧬] DefaultInboundAction set to Block. But Defender let Excel spawn PowerShell with -nop -w hidden anyway.",
"[🧬] DefaultInboundAction set to Block. But Defender let Excel spawn PowerShell with -nop -w hidden anyway.",
"[🔒] ...Your firewall is now a fortress. If only the OS wasn’t a secret passage.",
"[🔒] ...Your firewall is now a fortress. If only the OS wasn’t a secret passage.",
"[🚫] Domain profile hardened. Your AD still uses RC4, but hey — baby steps.",
"[🚫] Domain profile hardened. Your AD still uses RC4, but hey — baby steps.",
"[📊] Your profiles are hardened. And yet... svchost.exe still connects to 37 IPs before you even log in.",
"[📊] Your profiles are hardened. And yet... svchost.exe still connects to 37 IPs before you even log in.",
"[📶] Public profile locked. That open Wi-Fi named 'FBI Surveillance Van' is crying.",
"[🛸] ...Alien tech doesn’t have RDP exposed by default. We tried our best to match that."
)
$tsEnd = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
Write-Host "`n[👽] $tsEnd - Firewall hardening complete. Secure as can be (until next Windows update)." -ForegroundColor Cyan
Write-Host ""
Write-Host ($messages | Get-Random) -ForegroundColor DarkYellow
}