Repository navigation
Expand file tree
/
Copy pathFMRegJump.ps1
More file actions
440 lines (380 loc) · 15.7 KB
/
Copy pathFMRegJump.ps1
File metadata and controls
440 lines (380 loc) · 15.7 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
using namespace Microsoft.VisualBasic
using namespace System.Windows.Forms
using namespace System.Diagnostics
using namespace System.IO
using namespace System.Security.Principal
param (
[Parameter(
Position = 0,
HelpMessage = "The file whose extension determines which registry " +
"key to open in RegEdit or Registry Finder."
)]
[string] $InputFile,
[Parameter(
HelpMessage = "Root hive path for the extension lookup: " +
"'SystemFileAssociations' or 'HKEY_CLASSES_ROOT'."
)]
[ValidateSet('SystemFileAssociations', 'HKEY_CLASSES_ROOT')]
[string] $InputFileRoot = 'SystemFileAssociations',
[Parameter(
HelpMessage = "Override file input with a preset registry key."
)]
[ValidateSet(
'DirectoryBackground', 'Directory', 'DesktopBackground',
'AllFileSystemObjects', 'AllFiles', 'Drive', 'MyComputer',
'EnvVariablesCurrentUser', 'EnvVariablesSystem', 'Folder'
)]
[string] $PresetDestination,
[Parameter(
HelpMessage = "Which application to use for registry navigation."
)]
[ValidateSet('RegistryFinder', 'RegEdit')]
[string] $AppToUse = 'RegistryFinder',
[Parameter(
HelpMessage = "Re-use a single instance instead of opening " +
"multiple windows."
)]
[switch] $SingleInstance
)
# ── Resolve script/exe directory (ps2exe-safe) ──────────────
[string] $ScriptDir = if ($PSScriptRoot) {
$PSScriptRoot
} else {
[string] $exePath = [Environment]::GetCommandLineArgs()[0]
if ($exePath) {
Split-Path -Parent -Path (Convert-Path -LiteralPath $exePath)
} else { '.' }
}
# ─────────────────────────────────────────────────────────────────────────────────────────────
# Region - INTERNAL FUNCTIONS
# ─────────────────────────────────────────────────────────────────────────────────────────────
function Invoke-InternalMessageBox {
[CmdletBinding()]
[OutputType([string])]
param (
[Parameter(Position = 0, Mandatory)]
[ValidateNotNullOrEmpty()]
[string] $Prompt,
[ValidateNotNullOrEmpty()]
[string] $Title = 'FMRegJump',
[ValidateSet('Information', 'Question', 'Critical', 'Exclamation')]
[string] $Icon = 'Information',
[ValidateSet(
'OKOnly', 'OKCancel', 'AbortRetryIgnore',
'YesNoCancel', 'YesNo', 'RetryCancel'
)]
[string] $BoxType = 'OKOnly',
[ValidateSet(1, 2, 3)]
[int] $DefaultButton = 1,
[switch] $NonTopMost
)
if (-not ('FMDevToolbox.Win32.DpiHelper' -as [type])) {
Add-Type -AssemblyName System.Windows.Forms
Add-Type -TypeDefinition @'
using System.Runtime.InteropServices;
namespace FMDevToolbox.Win32 {
public static class DpiHelper {
[DllImport("user32.dll")]
public static extern bool SetProcessDPIAware();
}
}
'@ -Language CSharp
[void][FMDevToolbox.Win32.DpiHelper]::SetProcessDPIAware()
[Application]::EnableVisualStyles()
}
[string] $boxEnumName = switch ($BoxType) {
'OKOnly' { 'OkOnly' }
'OKCancel' { 'OkCancel' }
default { $BoxType }
}
[MsgBoxStyle] $style =
[MsgBoxStyle]::$Icon -bor
[MsgBoxStyle]::$boxEnumName -bor
[MsgBoxStyle]::"DefaultButton$DefaultButton" -bor
$(if ($NonTopMost) {
[MsgBoxStyle]::ApplicationModal
} else {
[MsgBoxStyle]::SystemModal
})
[Interaction]::MsgBox($Prompt, $style, $Title) -as [string]
}
function Read-InternalTomlConfig {
[CmdletBinding()]
[OutputType([hashtable])]
param (
[Parameter(Mandatory)]
[string] $Path
)
if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) {
return $null
}
[hashtable] $config = @{}
foreach ($line in [File]::ReadAllLines($Path)) {
[string] $trimmed = $line.Trim()
# Skip blank lines, comments, and table headers
if (-not $trimmed -or
$trimmed.StartsWith('#') -or
$trimmed.StartsWith('[')) {
continue
}
# Match: key = 'value' or key = "value"
if ($trimmed -match
"^([A-Za-z0-9_-]+)\s*=\s*(['""])(.*)(\2)\s*$") {
$config[$Matches[1]] = $Matches[3]
}
}
return $config
}
function Invoke-InternalRegistryKey {
[CmdletBinding()]
param(
[Parameter(Mandatory, Position = 0)]
[ValidateNotNullOrEmpty()]
[string[]] $RegKey,
[switch] $SingleInstance
)
[string] $lastKeyPath =
'HKCU:\Software\Microsoft\Windows\CurrentVersion\Applets\Regedit'
[hashtable] $hiveMap = @{
'HKLM' = 'HKEY_LOCAL_MACHINE'
'HKCU' = 'HKEY_CURRENT_USER'
'HKU' = 'HKEY_USERS'
'HKCC' = 'HKEY_CURRENT_CONFIG'
'HKCR' = 'HKEY_CLASSES_ROOT'
}
[string[]] $keysToOpen = if ($SingleInstance) {
, $RegKey[0]
} else { $RegKey }
foreach ($key in $keysToOpen) {
[string] $normalized = $key.Trim() -replace ':\\\\?', '\'
foreach ($abbr in $hiveMap.Keys) {
if ($normalized -match "^$abbr\\") {
$normalized = $normalized -replace "^$abbr",
$hiveMap[$abbr]
break
}
}
$normalized = $normalized.TrimEnd('\')
[string] $testPath = $normalized
[bool] $found = $false
while ($testPath) {
if (Test-Path -LiteralPath "Registry::$testPath") {
$found = $true
break
}
[string] $parent = Split-Path $testPath
if ($parent -eq $testPath) { break }
$testPath = $parent
}
if (-not $found) {
Invoke-InternalMessageBox `
-Prompt "Registry key not found:`n`n$key" `
-Icon 'Exclamation'
continue
}
Write-Verbose "Opening: $testPath"
Set-ItemProperty -LiteralPath $lastKeyPath `
-Name LastKey -Value $testPath -Force
[hashtable] $startParams = @{
FilePath = 'regedit'
Verb = 'RunAs'
PassThru = $true
}
if (-not $SingleInstance) {
$startParams.ArgumentList = '-m'
}
[Process] $proc = Start-Process @startParams
# Wait up to 10 seconds for the window to appear
[int] $waited = 0
while ($proc.MainWindowHandle -eq 0 -and $waited -lt 10000) {
Start-Sleep -Milliseconds 100
$waited += 100
}
if ($proc.MainWindowHandle -eq 0) {
Invoke-InternalMessageBox `
-Prompt ("RegEdit failed to open within 10 seconds." +
"`n`nThe UAC prompt may have been dismissed.") `
-Icon 'Critical'
}
}
}
function New-InternalVerboseLog {
[CmdletBinding()]
[OutputType([string])]
param (
[Parameter(Mandatory,Position=0)]
[ValidateNotNullOrEmpty()]
[string] $Message,
[ValidateSet("ERROR", "WARNING", "INFO", "SUCCESS", "DEBUG")]
[string] $Level = "INFO",
[switch] $IncludeCallerInfo,
[switch] $PassThru
)
$vLevel = $Level.ToUpper()
$ts = [DateTime]::UtcNow.ToString("yyyy-MM-dd HH:mm:ss")
$prefix = "[$ts] [$vLevel]"
if ($IncludeCallerInfo) {
$caller = (Get-PSCallStack)[1].FunctionName
$prefix += " [$caller]"
}
$formatted = "${prefix} $Message"
Write-Verbose $formatted
if ($PassThru) { $formatted }
}
# EndRegion
# ─────────────────────────────────────────────────────────────────────────────────────────────
# Region - VALIDATION
# ─────────────────────────────────────────────────────────────────────────────────────────────
# Mutual exclusivity
if ($InputFile -and $PresetDestination) {
Invoke-InternalMessageBox `
-Prompt ("-InputFile and -PresetDestination are mutually" +
" exclusive. Provide one or the other.") `
-Icon 'Critical'
return
}
# At least one input required
if (-not $InputFile -and -not $PresetDestination) {
Invoke-InternalMessageBox `
-Prompt ("No input provided. Pass either -InputFile or" +
" -PresetDestination.") `
-Icon 'Critical'
return
}
# Validate InputFile exists (when used)
if ($InputFile -and -not (Test-Path -LiteralPath $InputFile)) {
Invoke-InternalMessageBox `
-Prompt "The specified path does not exist:`n`n$InputFile" `
-Icon 'Critical'
return
}
# Registry Finder config validation (only when needed)
[string] $rfPath = $null
if ($AppToUse -eq 'RegistryFinder') {
[string] $configPath = Join-Path $ScriptDir 'FMRegJumpConfig.toml'
New-InternalVerboseLog -Message "Config Path Loaded: $configPath" -Level INFO
if (-not (Test-Path -LiteralPath $configPath -PathType Leaf)) {
New-InternalVerboseLog -Message "Configuration file not found: $configPath" -Level ERROR
Invoke-InternalMessageBox `
-Prompt "Configuration file not found:`n`n$configPath" `
-Icon 'Critical'
return
}
[hashtable] $config = Read-InternalTomlConfig -Path $configPath
New-InternalVerboseLog -Message "Configuration file loaded: `n`n$($config.ToString())" -Level INFO
if (-not $config -or -not $config['RegistryFinderPath']) {
New-InternalVerboseLog -Message "Missing 'RegistryFinderPath' in config." -Level ERROR
Invoke-InternalMessageBox `
-Prompt ("Missing 'RegistryFinderPath' in config:" +
"`n`n$configPath") `
-Icon 'Critical'
return
}
$rfPath = $config['RegistryFinderPath']
New-InternalVerboseLog -Message "Extracted Registry Finder Path from TOML Config: $rfPath" -Level SUCCESS
# Accept .exe (preferred — GUI subsystem, no console window) or .com (legacy —
# console subsystem, spawns a console window alongside Registry Finder).
if ([Path]::GetExtension($rfPath) -notin @('.com', '.exe')) {
New-InternalVerboseLog -Message "Registry Finder Path from TOML must be .exe or .com." -Level ERROR
Invoke-InternalMessageBox `
-Prompt ("RegistryFinderPath must point to a .exe or .com file." +
"`n`nCurrent value:`n$rfPath") `
-Icon 'Critical'
return
}
if (-not (Test-Path -LiteralPath $rfPath -PathType Leaf)) {
New-InternalVerboseLog -Message "Registry Finder not found at '$rfPath'" -Level ERROR
Invoke-InternalMessageBox `
-Prompt "Registry Finder not found at:`n`n$rfPath" `
-Icon 'Critical'
return
}
}
# EndRegion
# ─────────────────────────────────────────────────────────────────────────────────────────────
# Region - KEY RESOLUTION
# ─────────────────────────────────────────────────────────────────────────────────────────────
[string] $key = ''
if ($PresetDestination) {
[string] $cuSID =
[System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value
[hashtable] $presets = @{
DirectoryBackground = 'HKCR\Directory\Background\shell'
Directory = 'HKCR\Directory\shell'
Folder = 'HKCR\Folder'
DesktopBackground = 'HKCR\DesktopBackground\shell'
AllFileSystemObjects = 'HKCR\AllFileSystemObjects\shell'
AllFiles = 'HKCR\*\shell'
Drive = 'HKCR\Drive\shell'
MyComputer = 'HKCR\CLSID\{20D04FE0-3AEA-1069-A2D8-08002B30309D}\shell'
EnvVariablesCurrentUser = "HKU\$cuSID\Environment"
EnvVariablesSystem = 'HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment'
}
$key = $presets[$PresetDestination]
}
else {
if (Test-Path -LiteralPath $InputFile -PathType Leaf) {
[string] $ext = [Path]::GetExtension($InputFile)
[string] $root = if ($InputFileRoot -eq 'SystemFileAssociations') {
"HKCR\SystemFileAssociations\$ext"
} else { "HKCR\$ext" }
$key = "$root\Shell"
}
elseif (Test-Path -LiteralPath $InputFile -PathType Container) {
$key = 'HKCR\Directory\shell'
}
}
# Safety net: key must be resolved before launching anything
if (-not $key) {
Invoke-InternalMessageBox `
-Prompt ("Could not determine a registry key from the" +
" provided input.") `
-Icon 'Critical'
return
}
New-InternalVerboseLog -Message "Registry Key has been populated: '$key'" -Level INFO
# EndRegion
# ─────────────────────────────────────────────────────────────────────────────────────────────
# Region - LAUNCH APPLICATION
# ─────────────────────────────────────────────────────────────────────────────────────────────
if ($AppToUse -eq 'RegistryFinder') {
New-InternalVerboseLog -Message "App to launch is Registry Finder. Building arguments." -Level INFO
[hashtable] $rfStartParams = @{
FilePath = $rfPath
PassThru = $true
}
# Build argument list
[string[]] $rfArgs = @()
if (-not $SingleInstance) { $rfArgs += '--multiInst' }
$rfArgs += '--navigate'
$rfArgs += $key
$rfStartParams.ArgumentList = $rfArgs
New-InternalVerboseLog -Message "Pre Registry Finder Call, the arguments are: $rfArgs" -Level INFO
# We're already elevated via the SELF-ELEVATION region, so Registry Finder
# inherits our admin token. No -Verb RunAs needed (which would fail anyway:
# .com has no 'runas' shell verb on Windows 10/11). No auto-elevating compat
# flag needed on Registry Finder either.
[Process] $rfProc = Start-Process @rfStartParams
# Wait up to 10 seconds for the window to appear
[int] $waited = 0
while ($rfProc.MainWindowHandle -eq 0 -and $waited -lt 10000) {
Start-Sleep -Milliseconds 100
$waited += 100
}
if ($rfProc.MainWindowHandle -eq 0) {
Invoke-InternalMessageBox `
-Prompt "Registry Finder failed to open within 10 seconds." `
-Icon 'Critical'
}
New-InternalVerboseLog -Message "Registry Finder was called." -Level INFO
}
else {
New-InternalVerboseLog -Message "App to launch is RegEdit. Building arguments." -Level INFO
[hashtable] $regeditSplat = @{
RegKey = $key
SingleInstance = $SingleInstance
}
Invoke-InternalRegistryKey @regeditSplat
New-InternalVerboseLog -Message "RegEdit was called." -Level INFO
}
# EndRegion