-
Notifications
You must be signed in to change notification settings - Fork 0
/
_PS-WinHelpers.ps1
1801 lines (1444 loc) · 50.3 KB
/
_PS-WinHelpers.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
<#PSScriptInfo
.VERSION 2023.03.22
.AUTHOR Levente Rog
.COPYRIGHT (c) 2023 Levente Rog
.LICENSEURI https://github.com/levid0s/useful/blob/master/LICENSE.md
.PROJECTURI https://github.com/levid0s/useful/
#>
<#
.SYNOPSIS
A collection of PowerShell functions for common tasks.
.EXAMPLE
. ./_PS-WinHelpers.ps1
Write-Host "PowerShell script path: $(Get-ScriptPath)"
Write-Host "Running as admin: $(IsAdmin)"
Create-Shortcut -TargetPath 'C:\Windows\System32\cmd.exe' -ShortcutPath 'C:\Users\Public\Desktop\cmd.lnk' -Arguments '/k "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe"'
#>
###
### PowerShell Scripting Helpers
###
function IsAdmin {
<#
.SYNOPSIS
Returns $True if the script is running with elevated privileges
.EXAMPLE
if (IsAdmin) { Write-Host "Running as admin" }
#>
$currentPrincipal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
$currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
}
function Invoke-ToAdmin {
<#
.VERSION 2023.04.29
.SYNOPSIS
Elevates the current PowerShell script to admin privileges.
If UAC is enbled, the user will get a UAC prompt.
.EXAMPLE
if(!IsAdmin) {
Invoke-ToAdmin; Return
}
else {
Write-Host "Doing stuff as admin."
}
.TODO
- Add support for setting the working directory, as the -WorkingDirectory parameter is not working.
#>
param(
[hashtable]$CustomArguments = @{}
)
If (([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]'Administrator')) {
Write-DebugLog 'Already admin, nothing to do.'
Return
}
$PsCmd = (Get-ChildItem -Path "$PSHome\pwsh*.exe", "$PSHome\powershell*.exe")[0]
Write-Information 'Elevating script to Admin..'
$ScriptPath = (Get-PSCallStack)[1].ScriptName
$ScriptDir = (Get-PSCallStack)[1].ScriptName | Split-Path -Parent
$ArgHashtable = @{}
$ArgumentsString = (Get-PSCallStack)[1].Arguments.TrimStart('{').TrimEnd('}')
foreach ($a in ($ArgumentsString -split ',\s*')) {
$k, $v = $a -split '\s*=\s*'
if ($k -eq 'InvokeToAdmin') { continue }
$ArgHashtable[$k] = $v
}
# Overwrite any arguments with custom ones
foreach ($k in $CustomArguments.Keys) {
$ArgHashtable[$k] = $CustomArguments[$k]
}
# Build the $ArgumentList string
$cmd = Get-Command $ScriptPath
$params = $cmd.Parameters
$ArgumentList = @('-File', $ScriptPath)
foreach ($k in $ArgHashtable.Keys) {
$v = $ArgHashtable[$k]
switch ($params[$k].ParameterType) {
'bool' {
$ArgumentList += "-${k}"
$v = $v -in @('true', $true)
$ArgumentList += '$' + $v.ToString().ToLower()
}
'switch' {
if ($v -in @('true', $true)) {
$ArgumentList += "-${k}"
}
}
default {
$ArgumentList += "-${k}"
if ($null -eq $v) {
$v = '$null'
}
$ArgumentList += $v
}
}
}
Write-Debug "ScriptPath: $ScriptPath"
Write-Debug "ScriptDir: $ScriptDir"
Write-Debug "Arguments: $(Expand-Hashtable $ArgumentList)"
Write-DebugLog "Start-Process $PsCmd -Verb runAs -ArgumentList $(Expand-Hashtable $ArgumentList) -WorkingDirectory $ScriptDir"
# -Verb runAs `
Start-Process "$PsCmd" `
-Verb runAs `
-ArgumentList $ArgumentList `
-WorkingDirectory $ScriptDir
}
function Install-ModuleIfNotPresent {
<#
.SYNOPSIS
Install a module if it is not already present
.EXAMPLE
Install-ModuleIfNotPresent 'PowerShell-YAML'
#>
param(
[string]$ModuleName,
[ValidateSet('AllUsers', 'CurrentUser')][string]$Scope = 'CurrentUser'
)
if (!(Get-Module $ModuleName -ListAvailable -ErrorAction SilentlyContinue)) {
Install-Module $ModuleName -Scope $Scope
}
}
function Get-ScriptPath {
<#
.SYNOPSIS
Returns the full path to the powershell running script.
.EXAMPLE
Write-Host "Script path: $(Get-ScriptPath)"
#>
return (Get-PSCallStack)[1].ScriptName | Split-Path -Parent
}
function Write-DebugLog {
<#
.SYNOPSIS
Script for writing debug messages to the console, with additional information like the function name.
.DESCRIPTION
✓ Function name automatically added to the message.
✓ Output is padded based on the depth of the call.
✓ Control the level of debug information presented using the $DEBUGDEPTH global variable.
✓ Uses `Write-Debug`, so make sure: $DebugPreference='Continue'
.EXAMPLE
Write-DebugLog "Hello World"
.Example_output
# DEBUG: >> [ Invoke-Something ]: Running task `assocs` for Somethiing : System.Collections.Hashtable System.Collections.Hashtable System.Collections.Hashtable
# DEBUG: >>>> [ Update-FileAssocsExt ]: Creating assoc for jpg -> `N:\Tools\FSViewer\FSViewer.exe` : ``
# DEBUG: >>>>>> [ Test-Function ]: Hello, world!
#>
param(
[string]$Message,
[string]$LogLevel = 'DEBUG',
[string]$Header = 'Data'
)
$Caller = (Get-PSCallStack)[1].Command
# Get depth of call. 0 = main script, 1 = Helper ps1 , 2 = Write-DebugLog. Level any negative value to 0
$Depth = 0, ((Get-PSCallStack).Count - 3) | Measure-Object -Maximum | Select-Object -ExpandProperty Maximum # Main script is 0
if ($null -eq $DEBUGDEPTH) {
# Default value, if not already set via a global var
$DEBUGDEPTH = 2
}
if ($Depth -gt $DEBUGDEPTH -and $LogLevel -in @('VERBOSE', 'DEBUG')) { return }
if (!$DEBUGDEPTH) { $MaxDepth = 4 * 2 }
else { $MaxDepth = $DEBUGDEPTH * 2 }
$FrontPadChar = '>'
$FrontPadVal = $Depth * 2
$FrontPadding = $FrontPadChar * $FrontPadVal + ' ' * [math]::Sign($FrontPadVal)
# $FrontPadding = $FrontPadding.PadRight($MaxDepth, ' ')
$MidPadChar = '>'
$MidPadVal = $Depth * 0
$MidPadding = $MidPadChar * $MidPadVal + ' ' * [math]::Sign($MidPadVal)
switch ($LogLevel) {
'VERBOSE' {
if ($Message -match '\r\n|\n|\r') {
# Multiline message
Write-Verbose "${FrontPadding}[ ${Caller} ]:`n======================== Start of $Header =====================`n${Message}========================= End of $Header ======================"
}
else {
Write-Verbose "${FrontPadding}[ ${Caller} ]: ${MidPadding}${Message}"
}
}
'DEBUG' { Write-Debug "${FrontPadding}[ ${Caller} ]: ${MidPadding}${Message}" }
'INFO' {
# Workaround for https://stackoverflow.com/questions/55191548/write-information-does-not-show-in-a-file-transcribed-by-start-transcript
# InformationPreference should be = ??
Write-Information "${FrontPadding}[ ${Caller} ]: ${MidPadding}${Message}"
[System.Console]::WriteLine("INFO: ${FrontPadding}[ ${Caller} ]: ${MidPadding}${Message}")
}
'WARN' { Write-Warning "${FrontPadding}[ ${Caller} ]: ${MidPadding}${Message}" }
'ERROR' { Write-Error "${FrontPadding}[ ${Caller} ]: ${MidPadding}${Message}" -ErrorAction Continue }
default { throw 'Unknown Log Level.' }
}
}
function Start-SleepOrKey {
<#
.VERSION 20230322
.SYNOPSIS
Similar to Start-Sleep, but sleep is cancelled on any keypress.
.EXAMPLE
do {
Write-Host "Doing stuff..."
$key = Start-SleepOrKey -Seconds 10
if ($key.Character -eq 'q' ) {
Write-Host "Quitting.."
break
}
} while ($true)
#>
param(
[int]$Seconds
)
$key = $null
$startTime = Get-Date
while (((Get-Date) - $startTime) -lt [TimeSpan]::FromSeconds($Seconds)) {
if ($Host.UI.RawUI.KeyAvailable) {
$key = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown')
return $key
}
Start-Sleep -Milliseconds 100 # Wait for 100 milliseconds before checking again
}
}
function Start-SleepUntilTrue {
<#
.VERSION 20230330
.SYNOPSIS
Pause execution until a condition is met or a timeout is reache
.DESCRIPTION
The condition is considered met, once the scriptblock returns a value that is different from `$null` or `$false`.
Function passes through the result of `{ Condition }`, so it can be used in a variable assignment.
.EXAMPLE
$result = Start-SleepUntilTrue -Condition { Get-Process -Name "notepad" } -Seconds 10
#>
param(
[ScriptBlock]$Condition,
[int]$Seconds = 5
)
$startTime = Get-Date
$result = & $Condition
while (!(((Get-Date) - $startTime) -gt [TimeSpan]::FromSeconds($Seconds) -or $result)) {
Start-Sleep -Milliseconds 300
$result = & $Condition
}
return $result
}
Function Start-SleepUntilTrueEx {
<#
.VERSION 20230415
.SYNOPSIS
A more advanced version of Start-SleepUntilTrue, with exponential backoff and a check condition.
.DESCRIPTION
The function keeps executing the code from the Do and Check scriptblocks, until the a condition is considered met, as follows:
- If a Check block was provided, success depends if the Check block returns `$true`.
- If no Check block was provided, success depends if the Do block returns a value that is different from `$null` or `$false`.
- If the timeout has been reached, the function returns `$false`.
TODO: Output
.PARAMETER ExponentialBackoff
If set, the delay between each round will be doubled.
.PARAMETER MaxTimeoutMs
Maximum timeout in milliseconds.
If this is set, the function will exit when the timeout is reached, even if the total number of rounds have not been completed.
.EXAMPLE
# Wait for the notepad process to start
Start-SleepUntilTrueEx `
-Do {
Get-Process notepad -ErrorAction SilentlyContinue
}
.EXAMPLE
# Poll creating a user until it's successful, with exponential backoff.
Start-SleepUntilTrueEx `
-InitialDelayMs 1000 `
-ExponentialBackoff `
-Do {
curl.exe -X POST 'https://example.com/api/create-user' --data-raw '{ "username": "johndoe", "email": "[email protected]", "password": "secretpassword"}'
} `
-Check {
curl.exe 'https://example.com/api/user?id=johndoe'
}
#>
param(
[int]$Rounds = 5,
[int]$InitialDelayMs = 100,
[int]$MaxTimeoutMs,
[switch]$ExponentialBackoff,
[scriptblock]$Do = {},
[scriptblock]$Check = {}
)
$CheckResult = $null
$startTime = Get-Date
for ($round = 1; $round -le $rounds; $round++) {
if ($round -gt 1) {
Write-Verbose "Check condition not met, retrying with exponential backoff, round $round. Sleeping for $InitialDelayMs ms.."
Start-Sleep -Milliseconds $InitialDelayMs
if ($ExponentialBackoff) {
$InitialDelayMs *= 2
}
}
if ($MaxTimeoutMs) {
$elapsedTime = (Get-Date) - $startTime
if ($elapsedTime.TotalMilliseconds -gt $MaxTimeoutMs) {
Throw "Check condition not met after $Rounds rounds. Timeout reached."
}
}
try {
$DoResult = & $Do
$DoSuccess = $true
}
catch {
$DoSuccess = $false
}
# If a Check block was provided, success depends if the Check block returns $true.
if ($Check.ToString()) {
$CheckResult = & $Check
if (!$CheckResult) {
Continue
}
}
else {
# If no Check block was provided, success depends if the Do block doesn't throw an error.
if (!$DoSuccess) {
Continue
}
}
Write-Verbose 'Check condition met, exiting loop.'
return @{DoResult = $DoResult; CheckResult = $CheckResult }
}
Throw "Check condition not met after $Rounds rounds."
}
Function Get-SubstedPaths {
<#
.VERSION 20230406
.SYNOPSIS
Get a Hashtable of the currently Substed drives
.EXAMPLE
Get-SubstedPaths
Name Value
---- -----
M: D:\Dropbox\Music
N: D:\Dropbox
#>
$SubstOut = $(subst)
$SubstedPaths = @{}
$SubstOut | ForEach-Object {
$SubstedPaths[($_ -Split '\\: => ')[0]] = ($_ -Split '\\: => ')[1]
}
return $SubstedPaths
}
Function Get-RealPath {
<#
.VERSION 20230619
.SYNOPSIS
Returns the real path of a file or folder if the current path is on a substed drive
.DESCRIPTION
✓ If path is a substed drive, it's resolved to the real location
✓ If path is a symlink or junction, it's resolved to the real location
✓ Use -Go parameter to change the shell location instead of returning the path
.EXAMPLE
Get-RealPath
Get-RealPath .
Get-RealPath n:\tools
Get-RealPath -Go # will Push-Location to real directory
#>
param(
[string]$Path,
[switch]$Go
)
if ([string]::IsNullOrEmpty($Path)) {
$Path = $PWD.Path
}
$Path = (Resolve-Path $Path).Path
$SubstedPaths = Get-SubstedPaths
if ($SubstedPaths.Keys -contains $Path.Substring(0, 2)) {
$RealPath = $SubstedPaths[$Path.Substring(0, 2)] + $Path.Substring(2).TrimEnd('\')
}
else {
$RealPath = $Path.TrimEnd('\')
}
$RealPath = Get-Item -Path $RealPath
if ($RealPath.Target) {
$RealPath = $RealPath.Target
}
else {
$RealPath = $RealPath.FullName
}
if ($Go) {
Push-Location $RealPath
}
else {
return $RealPath
}
}
function Get-RealGitRoot {
<#
.VERSION 20230407
.SYNOPSIS
Returns the git root of a file or folder
.DESCRIPTION
✓ If path is a substed drive, it's resolved to the real location
✓ If path is inside a git repo, it's resolved to the git root
✓ If path is pointing to a file, it's resolved to the parent directory
.EXAMPLE
Get-RealGitRoot .
Get-RealGitRoot n:/src/useful/scripts
#>
param(
[Parameter(Mandatory = $true)][string]$Location,
[bool]$ResolveSubst = $true
)
if ($ResolveSubst) {
$RealPath = Get-RealPath $Location
}
else {
$RealPath = Resolve-Path $Location | Select -ExpandProperty Path
}
if (Test-Path $RealPath) {
$CheckPath = $RealPath
if (!(Test-Path $CheckPath -Type Container)) {
$CheckPath = Split-Path $RealPath -Parent
}
Write-Verbose "Check path is: $CheckPath"
Push-Location $CheckPath
$GitRoot = git rev-parse --show-toplevel 2>$null
if ($LASTEXITCODE -ne 0) {
$GitRoot = $CheckPath
Write-Verbose "Not a git repo. Keeping the real path: $CheckPath"
}
$RealPath = $GitRoot
Pop-Location
}
Return $RealPath | Resolve-Path
}
Function Get-Timestamp {
<#
.VERSION 20230407
#>
return Get-Date -Format 'yyyyMMdd-HHmmss'
}
Function Get-ShortGUID {
<#
.VERSION 20230407
#>
return (New-Guid).Guid.Split('-')[0]
}
function Get-StringHash {
<#
.VERSION 20230415
.SYNOPSIS
Returns the hash of a string
#>
param(
[Parameter(Mandatory = $true)][string]$String,
[ValidateSet('MD5', 'SHA1', 'SHA256', 'SHA384', 'SHA512')][string]$HashAlgorithm = 'SHA256'
)
$hasher = [System.Security.Cryptography.HashAlgorithm]::Create($HashAlgorithm)
$bytes = [System.Text.Encoding]::UTF8.GetBytes($String)
$hashBytes = $hasher.ComputeHash($bytes)
return [System.BitConverter]::ToString($hashBytes) -replace '-'
}
###
### Registry Manipulation Functions
###
function Get-RegValue {
<#
.VERSION 20230415
.SYNOPSIS
Reads a value from the registry
.DESCRIPTION
✓ This is a simplified version of the Get-ItemPropertyValue function.
✓ No need to specify the Value Name and Path in separate parameters.
✓ Supports multiple namings for the HKCU and HKLM root keys for convenience.
‼ By design, backslash in Value Name is not supported
.PARAMETER FullPath
The full path to the registry value, including the Value Name.
.PARAMETER ErrorAction
The error action to use when the registry value does not exist. Set it to SilentyContinue to return $null instead of throwing an error.
.EXAMPLE
Get-RegValue -FullPath 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders\Personal'
.EXAMPLE
Get-RegValue -FullPath 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders\Personal' -ErrorAction SilentlyContinue
#>
[CmdletBinding()]
param(
[string]$FullPath
)
$ErrorAction = $PSBoundParameters['ErrorAction']
if ([string]::IsNullOrEmpty($ErrorAction)) {
Write-Verbose "Setting default value for ErrorAction: 'Stop'"
$ErrorAction = 'Stop'
}
$Path = Split-Path $FullPath -Parent
$Path = $Path -replace '^(HKCU|HKEY_CURRENT_USER|HKEY_CURRENT_USER:)\\', 'HKCU:\'
$Path = $Path -replace '^(HKLM|HKEY_LOCAL_MACHINE|HKEY_LOCAL_MACHINE:)\\', 'HKLM:\'
$Name = Split-Path $FullPath -Leaf
# Get-ItemPropertyValue has a bug: https://github.com/PowerShell/PowerShell/issues/5906
$Value = Get-ItemProperty -LiteralPath $Path -Name $Name -ErrorAction $ErrorAction | Select-Object -ExpandProperty $Name
Return $Value
}
function Set-RegValue {
<#
.VERSION 20230429
.SYNOPSIS
Writes a value to the registry
.DESCRIPTION
A simplified and oppinionated version of the New-ItemProperty function:
✓ No need to specify Value Name and Path as separate parameters, just use FullPath="HKCU:\Path\To\Key\ValueName"
✓ Accepts various spellings of the `HKCU` and `HKLM` root keys for convenience.
✓ Autmatic data type detection for Value
✓ Auto-create the Path using the Force parameter
‼ By design, backslash in Value Name is not supported
.PARAMETER FullPath
The full path to the registry value, including the value name.
For default values, use (Default)
.PARAMETER Value
The value to write to the registry. This parameter is of string[] type but type conversion is performed automatically for other value type (DWORD, etc.).
.PARAMETER Type
The Value's data type to be written. Supports both the .Net (String) and the registry (REG_SZ) names for convenience.
.PARAMETER Force
Create the registry key (including the full path) if it does not exist.
.EXAMPLE
Set-RegValue -FullPath 'HKCU\SOFTWARE\Policies\Microsoft\Windows\Explorer\DisableSearchBoxSuggestions' -Value 1 -Type DWord
.EXAMPLE
Set-RegValue -FullPath 'HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced\MultiTaskingAltTabFilter' -Value 3 -Type REG_DWORD -Force
#>
param(
[string]$FullPath,
[object[]]$Value,
[Parameter(Mandatory = $true)][ValidateSet('String', 'REG_SZ', 'MultiString', 'REG_MULTI_SZ', 'ExpandString', 'REG_EXPAND_SZ', 'DWord', 'REG_DWORD', 'QWord', 'REG_QWORD', 'Binary', 'REG_BINARY')][string]$Type,
[switch]$Force
)
# Accept REG_* types for ease of use
$LookupTable = @{
'REG_SZ' = 'String'
'REG_EXPAND_SZ' = 'ExpandString'
'REG_BINARY' = 'Binary'
'REG_DWORD' = 'DWord'
'REG_MULTI_SZ' = 'MultiString'
'REG_QWORD' = 'QWord'
}
if ($LookupTable.ContainsKey($Type)) {
$Type = $LookupTable[$Type]
}
$Path = Split-Path $FullPath -Parent
$Path = $Path -replace '^(HKCU|HKEY_CURRENT_USER|HKEY_CURRENT_USER:)\\', 'HKCU:\'
$Path = $Path -replace '^(HKLM|HKEY_LOCAL_MACHINE|HKEY_LOCAL_MACHINE:)\\', 'HKLM:\'
$Name = Split-Path $FullPath -Leaf
if ($Force) {
if (!(Test-Path -LiteralPath $Path)) {
New-Item -Path $Path -Force
}
}
switch -wildcard ($Type) {
'String' { [string]$TargetValue = $Value }
'ExpandString' { [string]$TargetValue = $Value }
'MultiString' { [string[]]$TargetValue = $Value }
'Binary' { [byte[]]$TargetValue = $Value }
'DWord' { $TargetValue = [System.Convert]::ToUInt32($Value[0]) }
'QWord' { $TargetValue = [System.Convert]::ToUInt64($Value[0]) }
}
$CheckValues = (Get-ItemProperty -LiteralPath $Path).PSObject.Properties
if ($CheckValues.Name -contains $Name) {
$SourceValue = $CheckValues[$Name].Value
if ($null -in @($SourceValue, $TargetValue)) {
# Special exception for $null because Compare-Object doesn't support it
if ($SourceValue -eq $TargetValue) {
Write-DebugLog "Value already set: $Path\$Name = `$null ($Type)" -LogLevel Verbose
Return
}
}
elseif (!(Compare-Object -DifferenceObject $SourceValue -ReferenceObject $TargetValue -SyncWindow 0)) {
Write-DebugLog "Value already set: $Path\$Name = $TargetValue ($Type)" -LogLevel Verbose
Return
}
}
Write-DebugLog "Writing to registry: $Path\$Name = $TargetValue ($Type)"
$result = New-ItemProperty -LiteralPath $Path -Name $Name -Value $TargetValue -PropertyType $Type -Force
Return $result
}
###
### Scheduled Tasks
###
function Register-PowerShellScheduledTask {
<#
.VERSION 2023.10.02
.SYNOPSIS
Registers a PowerShell script as a **Hidden** Scheduled Task, ie a PowerShell window will not pop up during execution.
At the moment the schedule frequency is hardcoded to every 15 minutes.
.DESCRIPTION
Currently, it's not possible create a hidden Scheduled Task that executes a PowerShell task, meaning a command prompt
window will keep popping up every time the scheduled task is executed.
This function creates a wrapper vbs script that runs the PowerShell script as hidden.
source: https://github.com/PowerShell/PowerShell/issues/3028
.PARAMETER ScriptPath
The path to the PowerShell script that will be executed in the task.
.PARAMETER Parameters
A hashtable of parameters to pass to the script.
.PARAMETER TaskName
The Scheduled Task will be registered under this name in the Task Scheduler.
If not specified, the script name will be used.
.PARAMETER AllowRunningOnBatteries
Allows the task to run when the computer is on batteries.
.PARAMETER Uninstall
Unregister the Scheduled Task.
.PARAMETER ExecutionTimeLimit
The maximum amount of time the task is allowed to run.
New-TimeSpan -Hours 72
New-TimeSpan -Minutes 15
New-TimeSpan -Seconds 30
New-TimeSpan -Seconds 0 = Means disabled
.PARAMETER AsAdmin
Run the Scheduled Task as administrator.
.PARAMETER GroupId
The Scheduled Task will be registered under this group in the Task Scheduler.
Eg: "BUILTIN\Administrators"
.PARAMETER TimeInterval
The Scheduled Task will be triggered every X minutes.
.PARAMETER AtLogon
The Scheduled Task will be run at user logon.
.PARAMETER AtStartup
The Scheduled Task will be run at system startup. Requires admin rights.
.PARAMETER DailyAt
Start the task Daily at the specified time. Eg: "04:05"
#>
param(
[Parameter(Mandatory = $true, Position = 0)]$ScriptPath,
[hashtable]$Parameters = @{},
[string]$TaskName,
[int]$TimeInterval,
[switch]$AtLogon,
[switch]$AtStartup,
[string]$DailyAt,
[bool]$AllowRunningOnBatteries,
[switch]$DisallowHardTerminate,
[TimeSpan]$ExecutionTimeLimit,
[string]$GroupId,
[switch]$AsAdmin,
[switch]$Uninstall
)
if (!($TimeInterval -or $AtLogon -or $AtStartup -or $Uninstall -or $DailyAt)) {
Throw 'At least one of the following parameters must be defined: -TimeInterval, -AtLogon, -AtStartup, -DailyAt (or -Uninstall)'
}
if ([string]::IsNullOrEmpty($TaskName)) {
$TaskName = Split-Path $ScriptPath -Leaf
}
## Uninstall
if ($Uninstall) {
Stop-ScheduledTask -TaskName $TaskName -ErrorAction SilentlyContinue
Unregister-ScheduledTask -TaskName $TaskName -Confirm:$false
# Return $true if no tasks found, otherwise $false
return !(Get-ScheduledTask -TaskName $TaskName -ErrorAction SilentlyContinue)
}
## Install
if (!(Test-Path $ScriptPath)) {
Throw "Script ``$ScriptPath`` not found!"
}
$ScriptPath = Resolve-Path -LiteralPath $ScriptPath
# Create wrapper vbs script so we can run the PowerShell script as hidden
# https://github.com/PowerShell/PowerShell/issues/3028
if ($GroupId) {
$vbsPath = "$env:ALLUSERSPROFILE\PsScheduledTasks\$TaskName.vbs"
}
else {
$vbsPath = "$env:LOCALAPPDATA\PsScheduledTasks\$TaskName.vbs"
}
$vbsDir = Split-Path $vbsPath -Parent
if (!(Test-Path $vbsDir)) {
New-Item -ItemType Directory -Path $vbsDir
}
$ps = @(); $Parameters.GetEnumerator() | ForEach-Object { $ps += "-$($_.Name) $($_.Value)" }; $ps -join ' '
$vbsScript = @"
Dim shell, command, showWindow
showWindow = 0
' Check for Debug argument
Dim i, arg
For i = 0 To WScript.Arguments.Count - 1
arg = LCase(WScript.Arguments(i))
If arg = "-debug" Or arg = "/debug" Then
' Debug
showWindow = 1
Exit For
End If
Next
command = "powershell.exe -nologo -Command $ScriptPath $ps"
Set shell = CreateObject("WScript.Shell")
shell.Run command, 0, true
"@
Set-Content -Path $vbsPath -Value $vbsScript -Force
Get-ScheduledTask -TaskName $TaskName -ErrorAction SilentlyContinue -OutVariable TaskExists
if ($TaskExists.State -eq 'Running') {
Write-Debug "Stopping task for update: $TaskName"
$TaskExists | Stop-ScheduledTask
}
$action = New-ScheduledTaskAction -Execute $vbsPath
## Schedule
$triggers = @()
if ($TimeInterval) {
$t1 = New-ScheduledTaskTrigger -Daily -At 00:05
$t2 = New-ScheduledTaskTrigger -Once -At 00:05 `
-RepetitionInterval (New-TimeSpan -Minutes $TimeInterval) `
-RepetitionDuration (New-TimeSpan -Hours 23 -Minutes 55)
$t1.Repetition = $t2.Repetition
$t1.Repetition.StopAtDurationEnd = $false
$triggers += $t1
}
if ($AtLogOn) {
$triggers += New-ScheduledTaskTrigger -AtLogOn -User $env:USERNAME
}
if ($AtStartUp) {
$triggers += New-ScheduledTaskTrigger -AtStartup
}
if ($DailyAt) {
$triggers += New-ScheduledTaskTrigger -Daily -At $DailyAt
}
## Additional Options
$AdditionalOptions = @{}
if ($AsAdmin) {
$AdditionalOptions.RunLevel = 'Highest'
}
if ($GroupId) {
$STPrin = New-ScheduledTaskPrincipal -GroupId $GroupId
$AdditionalOptions.Principal = $STPrin
}
## Settings
$AdditionalSettings = @{}
if ($AllowRunningOnBatteries -eq $true) {
$AdditionalSettings.AllowStartIfOnBatteries = $true
$AdditionalSettings.DontStopIfGoingOnBatteries = $true
}
elseif ($AllowRunningOnBatteries -eq $false) {
$AdditionalSettings.AllowStartIfOnBatteries = $false
$AdditionalSettings.DontStopIfGoingOnBatteries = $false
}
if ($DisallowHardTerminate) {
$AdditionalSettings.DisallowHardTerminate = $true
}
if ($ExecutionTimeLimit) {
$AdditionalSettings.ExecutionTimeLimit = $ExecutionTimeLimit
}
$STSet = New-ScheduledTaskSettingsSet `
-MultipleInstances IgnoreNew `
@AdditionalSettings
## Decide if Register or Update
if (!$TaskExists) {
$cim = Register-ScheduledTask -Action $action -Trigger $triggers -TaskName $TaskName -Description "Scheduled Task for running $ScriptPath" -Settings $STSet @AdditionalOptions
}
else {
$cim = Set-ScheduledTask -TaskName $TaskName -Action $action -Trigger $triggers -Settings $STSet @AdditionalOptions
}
# Sometimes $cim returns more than 1 object, looks like a PowerShell bug.
# In those cases, get the last element of the list.
return $cim
}
###
### Shortcuts
###
function New-Shortcut {
<#
.SYNOPSIS
Creates a shortcut (.lnk) file.
✓ Has Unicode support, which wasn't present natively.
.PARAMETER Force
Overwrites the destination if it already exists.
.TODO
- Implement `Force` for non-unicode shortcuts
- Return the object that was created
#>
param(
[Parameter(Mandatory = $true)][string]$LnkPath,
[Parameter(Mandatory = $true)][string]$TargetExe,
[string[]]$Arguments,
[string]$WorkingDir,
[string]$IconPath,
[Parameter()][ValidateSet('Default', 'Minimized', 'Maximized')][string]$WindowStyle = 'Default',
[switch]$Force
)
if ((Test-Path -LiteralPath $LnkPath) -and !$Force) {
Write-DebugLog 'Link already exists, exiting.'
Return # "AlreadyExists"
}
if ($Force) {
$ForceParam = @{Force = $null }
}
else {
$ForceParam = @{ }
}
$bitWindowStyle = @{
Default = 1;
Maximized = 3;
Minimized = 7
}
$ParentPath = Split-Path $LnkPath -Parent
if (!(Test-Path $ParentPath)) {
New-Item -Path $ParentPath -ItemType Directory -Force -ErrorAction Stop | Out-Null
}
$nonASCII = '[^\x00-\x7F]'
$HasUnicode = $LnkPath -cmatch $nonASCII
if ($HasUnicode) {
$RealLnkPath = $LnkPath
$LnkPath = "$env:TEMP\$(New-Guid).lnk"
Write-DebugLog "$RealLnkPath has Unicode characters. Temp file is: $LnkPath" -LogLevel Verbose
}
if ($Arguments) {
Write-DebugLog "Arguments supplied: $Arguments" -LogLevel Verbose
}
$WshShell = New-Object -ComObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut($LnkPath)
$Shortcut.TargetPath = $TargetExe
$Shortcut.Arguments = $Arguments -join ' '
if ($IconPath) {
$Shortcut.IconLocation = $IconPath
}
$Shortcut.WorkingDirectory = $WorkingDir
$Shortcut.WindowStyle = $bitWindowStyle[$WindowStyle]
$Shortcut.Save()
if ($HasUnicode) {
Move-Item -Path $LnkPath -Destination $RealLnkPath @ForceParam
Write-DebugLog "Moved $LnkPath to $RealLnkPath" -LogLevel Verbose
}
$result = Get-Item $RealLnkPath
return $result
}
###
### Win32 Shell Class
###