-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStart-InSight.ps1
More file actions
6075 lines (5263 loc) · 258 KB
/
Start-InSight.ps1
File metadata and controls
6075 lines (5263 loc) · 258 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
<#
.SYNOPSIS
Launches the InSight WPF application.
.DESCRIPTION
Main entry point for the InSight.
.PARAMETER LogLevel
Logging level: Debug, Information, Warning, or Error.
.PARAMETER ConfigPath
Path to custom configuration file.
.EXAMPLE
.\Start-InSight.ps1
.EXAMPLE
.\Start-InSight.ps1 -LogLevel Debug
.NOTES
Author: Kosta Wadenfalk
GitHub: https://github.com/MrOlof
Requires: PowerShell 5.1+, Microsoft.Graph module
Version: 1.2.0
Changelog:
- v1.2.0: Reorganized backup folder structure to match Intune portal; Added logging for scripts without content
- v1.1.1: Fixed Configuration Backup issue with special characters in policy names (colons, slashes, etc.)
- v1.1.0: Device Ownership Analysis performance optimization and nested groups support
- v1.0.0: Initial release
#>
#Requires -Version 5.1
[CmdletBinding()]
param(
[Parameter()]
[ValidateSet('Debug', 'Information', 'Warning', 'Error')]
[string]$LogLevel = 'Information',
[Parameter()]
[string]$ConfigPath
)
# Hide PowerShell console window
Add-Type -Name Window -Namespace Console -MemberDefinition '
[DllImport("Kernel32.dll")]
public static extern IntPtr GetConsoleWindow();
[DllImport("user32.dll")]
public static extern bool ShowWindow(IntPtr hWnd, Int32 nCmdShow);
'
$consolePtr = [Console.Window]::GetConsoleWindow()
[Console.Window]::ShowWindow($consolePtr, 0) | Out-Null
# Set up PowerShell runspace for MSAL (required for MSAL.NET to work properly)
if (-not [System.Management.Automation.Runspaces.Runspace]::DefaultRunspace) {
$runspace = [System.Management.Automation.Runspaces.RunspaceFactory]::CreateRunspace()
$runspace.ApartmentState = 'STA'
$runspace.ThreadOptions = 'ReuseThread'
$runspace.Open()
[System.Management.Automation.Runspaces.Runspace]::DefaultRunspace = $runspace
}
$ErrorActionPreference = 'Stop'
#region Script Initialization
$ScriptRoot = $PSScriptRoot
$ModulesPath = Join-Path -Path $ScriptRoot -ChildPath 'Modules'
$ResourcesPath = Join-Path -Path $ScriptRoot -ChildPath 'Resources'
# Add required assemblies for WPF
Add-Type -AssemblyName PresentationFramework
Add-Type -AssemblyName PresentationCore
Add-Type -AssemblyName WindowsBase
Add-Type -AssemblyName System.Windows.Forms
# Import modules
$modules = @(
'LoggingManager',
'ConfigurationManager',
'AuthenticationManager',
'PermissionManager',
'ScriptManager',
'AssignmentHelpers'
)
foreach ($module in $modules) {
$modulePath = Join-Path -Path $ModulesPath -ChildPath "$module.psm1"
if (Test-Path -Path $modulePath) {
Import-Module $modulePath -Force -DisableNameChecking
Write-Verbose "Imported module: $module"
}
else {
throw "Required module not found: $modulePath"
}
}
# Initialize logging and configuration
Initialize-Logging -LogLevel $LogLevel
Initialize-Configuration -ConfigPath $ConfigPath
Write-LogInfo -Message "InSight starting..." -Source 'Launcher'
#endregion
#region XAML Loading
$xamlPath = Join-Path -Path $ResourcesPath -ChildPath 'MainWindow.xaml'
if (-not (Test-Path -Path $xamlPath)) {
throw "XAML file not found: $xamlPath"
}
$xamlContent = Get-Content -Path $xamlPath -Raw
# Create XML reader and load XAML
$reader = [System.Xml.XmlReader]::Create([System.IO.StringReader]::new($xamlContent))
$Window = [System.Windows.Markup.XamlReader]::Load($reader)
$reader.Close()
Write-LogInfo -Message "XAML loaded successfully" -Source 'Launcher'
#endregion
#region Control References
# Get references to named controls
$controls = @{}
$controlNames = @(
# Header authentication controls
'HeaderSignInButton', 'SigningInPanel', 'UserProfileSection', 'UserProfileButton', 'UserDropdownPopup',
'HeaderUserInitials', 'HeaderUserName', 'HeaderUserEmail',
# User dropdown menu
'MenuRefreshToken', 'MenuSettings', 'MenuSignOut',
# Search and Navigation
'SearchBox', 'NavigationPanel',
# Navigation buttons
'NavDashboard', 'NavApps', 'NavConfiguration', 'NavAssignments', 'NavDeviceOwnership',
'NavRemediation', 'NavBackup', 'NavReports',
# Views
'WelcomeView',
'DashboardView', 'ApplicationsView', 'ConfigurationsView', 'AssignmentsView', 'DeviceOwnershipView', 'ReportsView', 'PlaceholderView', 'SettingsView', 'RemediationScriptsView', 'BackupView',
'PlaceholderIcon', 'PlaceholderTitle', 'PlaceholderDescription', 'PlaceholderPermission',
# Reports view controls
'GenerateAuthReportButton', 'AuthReportStatusText', 'AuthReportResultsPanel', 'AuthReportResultMessage',
'OpenAuthReportButton', 'OpenAuthFolderButton',
'GenerateInactiveReportButton', 'InactiveReportStatusText', 'InactiveReportResultsPanel', 'InactiveReportResultMessage',
'OpenInactiveReportButton', 'OpenInactiveFolderButton',
'GenerateCAReportButton', 'CAReportStatusText', 'CAReportResultsPanel', 'CAReportResultMessage',
'OpenCAReportButton', 'OpenCAFolderButton', 'CAReportDaysComboBox',
'GenerateShadowITReportButton', 'ShadowITReportStatusText', 'ShadowITReportResultsPanel', 'ShadowITReportResultMessage',
'OpenShadowITReportButton', 'OpenShadowITFolderButton', 'ShadowITReportDaysComboBox',
# Remediation Scripts view controls
'RemediationSearchBox', 'RemediationCategoryFilter', 'RemediationResultsSummary', 'RemediationResultsCount',
'RemediationScriptsContainer', 'RemediationNoResults',
'CategoryAll', 'CategorySecurity', 'CategoryMaintenance', 'CategoryApplicationManagement',
'CategorySystemConfiguration', 'CategoryNetwork', 'CategoryUserExperience', 'CategoryTroubleshooting',
# Backup view controls
'BackupPathTextBox', 'BrowseBackupPathButton', 'IncludeAssignmentsCheckBox', 'ExcludeBuiltInCheckBox',
'BackupSelectAllCheckBox', 'BackupComplianceCheckBox', 'BackupConfigurationsCheckBox', 'BackupSettingsCatalogCheckBox',
'BackupScriptsCheckBox', 'BackupRemediationsCheckBox', 'BackupApplicationsCheckBox', 'BackupAutopilotCheckBox',
'BackupEndpointSecurityCheckBox', 'BackupAdminTemplatesCheckBox',
'ApiVersionV1RadioButton', 'ApiVersionBetaRadioButton', 'StartBackupButton', 'BackupLoadingText',
'BackupProgressCard', 'BackupProgressBar', 'BackupStatusText', 'BackupCurrentItemText',
'BackupResultsCard', 'BackupResultIcon', 'BackupResultTitle', 'BackupResultMessage',
'BackupStatsGrid', 'BackupItemsCount', 'BackupFilesCount', 'BackupDuration',
'OpenBackupFolderButton', 'NewBackupButton',
# Applications view controls
'AppsDataGrid', 'AppsEmptyState', 'LoadAppsButton', 'CheckVersionsButton', 'ExportAppsButton',
'AppsProgressCard', 'AppsProgressBar', 'AppsProgressText',
# Configurations view controls
'FetchAllConfigurationsButton', 'AdvancedSearchButton',
'ConfigProfilesLoadingText', 'ExportConfigProfilesButton', 'FetchConfigProfilesButton', 'BenchmarkConfigProfilesButton', 'SettingsCatalogButton', 'SettingsCatalogCount',
'DeviceRestrictionsButton', 'DeviceRestrictionsCount', 'AdminTemplatesButton', 'AdminTemplatesCount',
'EndpointSecLoadingText', 'ExportEndpointSecButton', 'FetchEndpointSecButton', 'BenchmarkEndpointSecButton', 'FirewallButton', 'FirewallCount', 'EDRButton', 'EDRCount',
'ASRButton', 'ASRCount', 'AccountProtectionButton', 'AccountProtectionCount',
'ConditionalAccessButton', 'ConditionalAccessCount',
'AppProtectionLoadingText', 'ExportAppProtectionButton', 'FetchAppProtectionButton', 'BenchmarkAppProtectionButton', 'AndroidAppProtectionButton', 'AndroidAppProtectionCount',
'iOSAppProtectionButton', 'iOSAppProtectionCount',
# Assignments view controls
'SearchDeviceGroupsButton', 'DeviceGroupSearchBox', 'FetchDeviceGroupAssignmentsButton', 'DeviceGroupResultsPanel',
'DeviceGroupRadio', 'SingleDeviceRadio', 'DeviceSearchInstructions',
'SearchUserGroupsButton', 'UserGroupSearchBox', 'FetchUserGroupAssignmentsButton', 'UserGroupResultsPanel',
'UserGroupRadio', 'SingleUserRadio', 'UserSearchInstructions',
'FindOrphanedButton', 'OrphanedLoadingText', 'NoAssignmentsCount', 'EmptyGroupsCount', 'TotalOrphanedCount', 'ExportOrphanedButton',
'ViewNoAssignmentsButton', 'ViewEmptyGroupsButton', 'ViewAllOrphanedButton',
# Device Ownership view controls
'SearchOwnershipGroupButton', 'OwnershipGroupSearchBox', 'AnalyzeOwnershipButton', 'IncludeNestedGroupsCheckBox',
'OwnershipLoadingText', 'OwnershipSummaryCards', 'OwnershipResultsPanel',
'NoDevicesCount', 'MultipleDevicesCount', 'SingleDeviceCount',
'ViewNoDevicesButton', 'ViewMultipleDevicesButton', 'ViewSingleDeviceButton', 'ExportOwnershipButton',
# Dashboard elements
'DeviceCountText', 'CompliantCountText', 'AppCountText', 'PolicyCountText',
'PermissionsGrid', 'RefreshPermissionsButton',
# Quick actions
'QuickActionDeviceSearch', 'QuickActionUserLookup', 'QuickActionExport', 'QuickActionRefresh',
# Settings
'DarkModeToggle', 'AnimationsToggle', 'CachingToggle', 'ExportPathTextBox', 'BrowseExportPath', 'ViewLogsButton',
# Status bar
'ConnectionIndicator', 'ConnectionStatusText', 'StatusMessageText', 'LastRefreshText', 'CurrentTimeText'
)
foreach ($name in $controlNames) {
$control = $Window.FindName($name)
if ($control) {
$controls[$name] = $control
}
}
#endregion
#region Theme Functions
function Update-Theme {
param([bool]$IsDark)
$colors = Get-ThemeColors
$resources = $Window.Resources
# Update brushes dynamically
$brushMappings = @{
'BackgroundBrush' = 'Background'
'BackgroundSecondaryBrush' = 'BackgroundSecondary'
'HeaderBrush' = 'BackgroundSecondary'
'SurfaceBrush' = 'Surface'
'SurfaceHoverBrush' = 'SurfaceHover'
'AccentBrush' = 'Accent'
'AccentHoverBrush' = 'AccentHover'
'AccentDarkBrush' = 'AccentDark'
'TextPrimaryBrush' = 'TextPrimary'
'TextSecondaryBrush' = 'TextSecondary'
'TextTertiaryBrush' = 'TextTertiary'
'TextDisabledBrush' = 'TextDisabled'
'TextOnAccentBrush' = 'TextOnAccent'
'BorderBrush' = 'Border'
'BorderLightBrush' = 'BorderLight'
'DividerBrush' = 'Divider'
'NavBackgroundBrush' = 'NavBackground'
'NavItemHoverBrush' = 'NavItemHover'
'NavItemSelectedBrush' = 'NavItemSelected'
'SuccessBrush' = 'Success'
'WarningBrush' = 'Warning'
'ErrorBrush' = 'Error'
'InfoBrush' = 'Info'
}
foreach ($brushName in $brushMappings.Keys) {
$colorKey = $brushMappings[$brushName]
if ($colors.ContainsKey($colorKey)) {
$colorValue = $colors[$colorKey]
try {
# Brushes in XAML are frozen (read-only), so we need to replace them entirely
$newColor = [System.Windows.Media.ColorConverter]::ConvertFromString($colorValue)
if ($newColor) {
# Create a new SolidColorBrush and replace the resource
$newBrush = New-Object System.Windows.Media.SolidColorBrush($newColor)
$resources[$brushName] = $newBrush
Write-LogDebug -Message "Updated brush: $brushName → $colorValue" -Source 'Theme'
}
}
catch {
Write-LogWarning -Message "Failed to update brush: $brushName - $_" -Source 'Theme'
}
}
}
Write-LogDebug -Message "Theme updated to: $(if ($IsDark) { 'Dark' } else { 'Light' })" -Source 'Theme'
}
#endregion
#region Navigation Functions
$script:CurrentView = 'Welcome'
$script:NavButtons = @{
'Dashboard' = @{ Button = $controls['NavDashboard']; Icon = [char]0xE80F; Feature = $null; Lock = $null }
'Applications' = @{ Button = $controls['NavApps']; Icon = [char]0xE71D; Feature = 'Apps.View' }
'Configuration' = @{ Button = $controls['NavConfiguration']; Icon = [char]0xE713; Feature = 'Configuration.View' }
'Assignments' = @{ Button = $controls['NavAssignments']; Icon = [char]0xE8F4; Feature = 'Assignments.View' }
'Device Ownership' = @{ Button = $controls['NavDeviceOwnership']; Icon = [char]0xE770; Feature = $null }
'Remediation' = @{ Button = $controls['NavRemediation']; Icon = [char]0xE90F; Feature = $null }
'Backup' = @{ Button = $controls['NavBackup']; Icon = [char]0xE8C8; Feature = $null }
'Reports' = @{ Button = $controls['NavReports']; Icon = [char]0xE9F9; Feature = 'Reports.Export' }
}
function Update-NavigationState {
# All navigation buttons are always enabled
foreach ($viewName in $script:NavButtons.Keys) {
$navInfo = $script:NavButtons[$viewName]
$button = $navInfo.Button
if ($button) {
$button.IsEnabled = $true
}
}
# Enable search box when authenticated
if ($controls['SearchBox']) {
$controls['SearchBox'].IsEnabled = $IsAuthenticated
}
}
function Show-View {
param(
[Parameter(Mandatory)]
[string]$ViewName
)
# Hide all views
if ($controls['WelcomeView']) { $controls['WelcomeView'].Visibility = 'Collapsed' }
if ($controls['DashboardView']) { $controls['DashboardView'].Visibility = 'Collapsed' }
if ($controls['ApplicationsView']) { $controls['ApplicationsView'].Visibility = 'Collapsed' }
if ($controls['ConfigurationsView']) { $controls['ConfigurationsView'].Visibility = 'Collapsed' }
if ($controls['AssignmentsView']) { $controls['AssignmentsView'].Visibility = 'Collapsed' }
if ($controls['DeviceOwnershipView']) { $controls['DeviceOwnershipView'].Visibility = 'Collapsed' }
if ($controls['ReportsView']) { $controls['ReportsView'].Visibility = 'Collapsed' }
if ($controls['PlaceholderView']) { $controls['PlaceholderView'].Visibility = 'Collapsed' }
if ($controls['SettingsView']) { $controls['SettingsView'].Visibility = 'Collapsed' }
if ($controls['RemediationScriptsView']) { $controls['RemediationScriptsView'].Visibility = 'Collapsed' }
if ($controls['BackupView']) { $controls['BackupView'].Visibility = 'Collapsed' }
$script:CurrentView = $ViewName
switch ($ViewName) {
'Welcome' {
$controls['WelcomeView'].Visibility = 'Visible'
}
'Dashboard' {
$controls['DashboardView'].Visibility = 'Visible'
Update-DashboardData
}
'Applications' {
$controls['ApplicationsView'].Visibility = 'Visible'
}
'Configuration' {
$controls['ConfigurationsView'].Visibility = 'Visible'
}
'Assignments' {
$controls['AssignmentsView'].Visibility = 'Visible'
}
'Device Ownership' {
$controls['DeviceOwnershipView'].Visibility = 'Visible'
}
'Remediation' {
$controls['RemediationScriptsView'].Visibility = 'Visible'
if ($script:RemediationScripts.Count -eq 0) {
Load-RemediationScripts
Show-RemediationScripts -SearchText "" -Category "All"
}
}
'Backup' {
$controls['BackupView'].Visibility = 'Visible'
}
'Reports' {
$controls['ReportsView'].Visibility = 'Visible'
}
'Settings' {
$controls['SettingsView'].Visibility = 'Visible'
}
default {
# Show placeholder for features not yet implemented
$navInfo = $script:NavButtons[$ViewName]
$featureId = $navInfo.Feature
if ($controls['PlaceholderIcon']) { $controls['PlaceholderIcon'].Text = [string]$navInfo.Icon }
if ($controls['PlaceholderTitle']) { $controls['PlaceholderTitle'].Text = $ViewName }
if ($controls['PlaceholderDescription']) {
# Custom description for Reports
if ($ViewName -eq 'Reports') {
$controls['PlaceholderDescription'].Text = "Generate beautiful HTML reports for Conditional Access policies, Intune configurations, compliance status, device inventory, application deployments, and much more. Export comprehensive documentation and compliance reports with rich formatting and interactive charts."
}
else {
$controls['PlaceholderDescription'].Text = "The $ViewName management feature will be available here. Add scripts to the Scripts folder to extend functionality."
}
}
if ($featureId -and $controls['PlaceholderPermission']) {
$access = Test-FeatureAccess -FeatureId $featureId
if (-not $access.HasAccess) {
$controls['PlaceholderPermission'].Text = "Missing permissions: $($access.MissingPermissions -join ', ')"
}
else {
$controls['PlaceholderPermission'].Text = ""
}
}
elseif ($controls['PlaceholderPermission']) {
$controls['PlaceholderPermission'].Text = ""
}
$controls['PlaceholderView'].Visibility = 'Visible'
}
}
Write-LogDebug -Message "View changed to: $ViewName" -Source 'Navigation'
}
function Update-SelectedNavButton {
param([string]$ViewName)
foreach ($name in $script:NavButtons.Keys) {
$button = $script:NavButtons[$name].Button
if ($button) {
if ($name -eq $ViewName) {
$button.Background = $Window.Resources['NavItemSelectedBrush']
$button.Foreground = $Window.Resources['AccentBrush']
}
else {
$button.Background = [System.Windows.Media.Brushes]::Transparent
$button.Foreground = $Window.Resources['TextSecondaryBrush']
}
}
}
}
#endregion
#region Dashboard Functions
function Update-DashboardData {
# Dashboard is now a static welcome screen - no data loading needed
# Just update permission display
Update-PermissionsDisplay
}
function Get-StringSimilarity {
param(
[string]$String1,
[string]$String2
)
# Simple similarity check - returns score 0-100
$s1 = $String1.ToLower() -replace '[^a-z0-9]', ''
$s2 = $String2.ToLower() -replace '[^a-z0-9]', ''
if ($s1 -eq $s2) { return 100 }
if ($s1.Contains($s2) -or $s2.Contains($s1)) { return 80 }
# Check first few characters
$minLen = [Math]::Min($s1.Length, $s2.Length)
if ($minLen -gt 0) {
$matchLen = 0
for ($i = 0; $i -lt $minLen; $i++) {
if ($s1[$i] -eq $s2[$i]) { $matchLen++ }
else { break }
}
return [int](($matchLen / $minLen) * 60)
}
return 0
}
function Compare-AppVersion {
param(
[string]$CurrentVersion,
[string]$LatestVersion
)
if ([string]::IsNullOrWhiteSpace($CurrentVersion) -or [string]::IsNullOrWhiteSpace($LatestVersion)) {
return "Unknown"
}
try {
# Try to parse as System.Version (handles x.y.z.w format)
$current = [System.Version]::Parse($CurrentVersion)
$latest = [System.Version]::Parse($LatestVersion)
if ($latest -gt $current) {
return "Yes ($LatestVersion)"
}
elseif ($latest -eq $current) {
return "Up to date"
}
else {
return "Newer installed"
}
}
catch {
# Version parsing failed, do simple string comparison
if ($CurrentVersion -ne $LatestVersion) {
return "Check ($LatestVersion)"
}
else {
return "Same version"
}
}
}
# Load WinGet package mappings once
$script:WinGetMappings = $null
function Get-WinGetMappings {
if ($null -eq $script:WinGetMappings) {
try {
$mappingPath = Join-Path $PSScriptRoot "Resources\WinGetPackageMappings.json"
if (Test-Path $mappingPath) {
$script:WinGetMappings = Get-Content -Path $mappingPath -Raw | ConvertFrom-Json
Write-LogInfo -Message "Loaded $($script:WinGetMappings.mappings.Count) WinGet package mappings" -Source "WinGetMappings"
}
else {
Write-LogWarning -Message "WinGet mappings file not found at: $mappingPath" -Source "WinGetMappings"
$script:WinGetMappings = @{ mappings = @() }
}
}
catch {
Write-LogError -Message "Failed to load WinGet mappings: $($_.Exception.Message)" -Source "WinGetMappings"
$script:WinGetMappings = @{ mappings = @() }
}
}
return $script:WinGetMappings
}
function Update-MappingPackageId {
param(
[string]$AppName,
[string]$PackageId
)
try {
$mappingPath = Join-Path $PSScriptRoot "Resources\WinGetPackageMappings.json"
if (-not (Test-Path $mappingPath)) {
Write-LogWarning -Message "Mapping file not found, cannot update" -Source "WinGetMappings"
return
}
# Load current mappings
$json = Get-Content -Path $mappingPath -Raw | ConvertFrom-Json
# Find and update the mapping
$updated = $false
foreach ($mapping in $json.mappings) {
foreach ($commonName in $mapping.commonNames) {
if ($commonName -eq $AppName) {
$mapping.packageId = $PackageId
$updated = $true
Write-LogInfo -Message "Updated mapping: '$AppName' -> $PackageId" -Source "WinGetMappings"
break
}
}
if ($updated) { break }
}
if ($updated) {
# Save updated mappings
$json | ConvertTo-Json -Depth 10 | Set-Content -Path $mappingPath -Encoding UTF8
# Invalidate cached mappings so they reload
$script:WinGetMappings = $null
}
}
catch {
Write-LogError -Message "Failed to update mapping for '$AppName': $($_.Exception.Message)" -Source "WinGetMappings"
}
}
function Find-WinGetPackageId {
param(
[string]$AppName,
[string]$Publisher
)
$mappings = Get-WinGetMappings
if (-not $mappings -or -not $mappings.mappings) {
Write-LogWarning -Message "No WinGet mappings loaded" -Source "WinGetMappings"
return $null
}
# Clean the app name for better matching
$cleanName = $AppName -replace '\s*(Enterprise|Professional|Updated|\(x64\)|\(x86\)|64-bit|32-bit|Client|App|Application|Desktop|Suite|Software)\s*', '' -replace '\s+', ' '
$cleanName = $cleanName.Trim()
foreach ($mapping in $mappings.mappings) {
# Check if app name matches any of the common names (exact match first)
foreach ($commonName in $mapping.commonNames) {
# Exact match (case-insensitive)
if ($AppName.ToLower() -eq $commonName.ToLower() -or $cleanName.ToLower() -eq $commonName.ToLower()) {
Write-LogInfo -Message "Found exact mapping: '$AppName' -> $($mapping.packageId)" -Source "WinGetMappings"
return $mapping.packageId
}
}
# Partial match with publisher verification
foreach ($commonName in $mapping.commonNames) {
$appLower = $AppName.ToLower()
$commonLower = $commonName.ToLower()
if ($appLower.Contains($commonLower) -or $commonLower.Contains($appLower)) {
# If publisher is available, verify it matches
if ($Publisher -and $mapping.publisher) {
$pubLower = $Publisher.ToLower()
$mapPubLower = $mapping.publisher.ToLower()
if ($pubLower -eq $mapPubLower -or $pubLower.Contains($mapPubLower) -or $mapPubLower.Contains($pubLower)) {
Write-LogInfo -Message "Found partial mapping with publisher: '$AppName' ($Publisher) -> $($mapping.packageId)" -Source "WinGetMappings"
return $mapping.packageId
}
}
# If no publisher info, accept the match
elseif (-not $Publisher -or -not $mapping.publisher) {
Write-LogInfo -Message "Found partial mapping: '$AppName' -> $($mapping.packageId)" -Source "WinGetMappings"
return $mapping.packageId
}
}
}
}
Write-LogInfo -Message "No mapping found for: '$AppName' (Publisher: $Publisher)" -Source "WinGetMappings"
return $null
}
function Get-WinGetPackageInfo {
param(
[string]$PackageId
)
try {
Write-LogInfo -Message "Fetching package info for: $PackageId" -Source "WinGet"
# Use local winget command to show package info
$output = & winget show --id $PackageId --exact --accept-source-agreements 2>&1
if ($LASTEXITCODE -eq 0 -and $output) {
# Parse the output to extract version
$versionLine = $output | Where-Object { $_ -match '^\s*Version:\s*(.+)$' } | Select-Object -First 1
if ($versionLine -match '^\s*Version:\s*(.+)$') {
$version = $Matches[1].Trim()
Write-LogInfo -Message "Got version $version for $PackageId" -Source "WinGet"
return @{
PackageId = $PackageId
Version = $version
Name = $PackageId
}
}
}
Write-LogWarning -Message "Could not get version info for $PackageId from winget" -Source "WinGet"
}
catch {
Write-LogError -Message "Failed to get WinGet package info for '$PackageId': $($_.Exception.Message)" -Source "WinGet"
}
return $null
}
function Search-WinGetRepository {
param(
[string]$AppName,
[string]$Publisher,
[string]$CurrentVersion
)
try {
# Clean the app name - remove common suffixes and words
$cleanName = $AppName -replace '\s*(Enterprise|Professional|Updated|\(x64\)|\(x86\)|64-bit|32-bit|Client|App|Application|Player|Desktop|Suite|Software)\s*', '' -replace '\s+', ' '
$cleanName = $cleanName.Trim()
# Try searching with cleaned name
$searchTerm = if ($cleanName) { $cleanName } else { $AppName }
Write-LogInfo -Message "Searching WinGet for: '$searchTerm' (Publisher: $Publisher)" -Source "WinGetSearch"
# Use local winget search command
$output = & winget search $searchTerm --accept-source-agreements 2>&1
if ($LASTEXITCODE -eq 0 -and $output) {
# Parse winget search output (format: Name Id Version Source)
$packages = @()
$inResults = $false
foreach ($line in $output) {
# Skip until we hit the separator line
if ($line -match '^-+\s+-+') {
$inResults = $true
continue
}
if ($inResults -and $line -match '\S') {
# Parse line: Name Id Version Source
# Split by multiple spaces (2 or more)
$parts = $line -split '\s{2,}' | Where-Object { $_ -ne '' }
if ($parts.Count -ge 3) {
$pkgName = $parts[0].Trim()
$pkgId = $parts[1].Trim()
$pkgVersion = $parts[2].Trim()
$packages += @{
Name = $pkgName
Id = $pkgId
Version = $pkgVersion
}
}
}
}
# Try to find best match
foreach ($pkg in $packages) {
# Exact name match
if ($pkg.Name -eq $AppName -or $pkg.Name -eq $cleanName) {
Write-LogInfo -Message "Found exact match: $($pkg.Id)" -Source "WinGetSearch"
return @{
Match = "[Available] - $($pkg.Id)"
PackageId = $pkg.Id
Confidence = "High"
LatestVersion = $pkg.Version
}
}
# Name similarity match
$similarity = Get-StringSimilarity -String1 $cleanName -String2 $pkg.Name
if ($similarity -gt 80) {
Write-LogInfo -Message "Found similar match: $($pkg.Id) (similarity: $similarity)" -Source "WinGetSearch"
return @{
Match = "[Available] - $($pkg.Id)"
PackageId = $pkg.Id
Confidence = "Medium"
LatestVersion = $pkg.Version
}
}
}
# If we found packages but no good match, return the first one as possible
if ($packages.Count -gt 0) {
$firstPkg = $packages[0]
return @{
Match = "[Possible] - $($firstPkg.Id)"
PackageId = $firstPkg.Id
Confidence = "Low"
LatestVersion = $firstPkg.Version
}
}
}
return @{ Match = "Not Found"; PackageId = $null; Confidence = "None"; LatestVersion = $null }
}
catch {
Write-LogError -Message "WinGet search failed for '$AppName': $($_.Exception.Message)" -Source "WinGetSearch"
return @{ Match = "Unknown"; PackageId = $null; Confidence = "None"; LatestVersion = $null }
}
}
function Find-StoreAlternative {
param(
[string]$DisplayName,
[string]$Publisher,
[string]$CurrentVersion,
[array]$WinGetApps
)
# First check in-tenant WinGet apps (fast)
$cleanName = $DisplayName -replace '\s*(Enterprise|Professional|Updated|\(x64\)|\(x86\)|64-bit|32-bit)\s*', ''
# Try exact match in tenant first
$exactMatch = $WinGetApps | Where-Object { $_.displayName -eq $DisplayName }
if ($exactMatch) {
$pkgId = if ($exactMatch.packageIdentifier) { " - $($exactMatch.packageIdentifier)" } else { "" }
return @{
Match = "[In Tenant]$pkgId"
PackageId = $exactMatch.packageIdentifier
Confidence = "High"
LatestVersion = $null
}
}
# Try publisher + name match in tenant
if ($Publisher) {
$publisherMatches = $WinGetApps | Where-Object {
$_.publisher -and $_.publisher -eq $Publisher
}
foreach ($match in $publisherMatches) {
$similarity = Get-StringSimilarity -String1 $cleanName -String2 $match.displayName
if ($similarity -gt 70) {
$pkgId = if ($match.packageIdentifier) { " - $($match.packageIdentifier)" } else { "" }
return @{
Match = "[In Tenant]$pkgId"
PackageId = $match.packageIdentifier
Confidence = "High"
LatestVersion = $null
}
}
}
}
# Not found in tenant - check local WinGet mappings database
$mappedPackageId = Find-WinGetPackageId -AppName $DisplayName -Publisher $Publisher
if ($mappedPackageId) {
# Check if packageId needs to be discovered
if ($mappedPackageId -eq "DISCOVER") {
Write-LogInfo -Message "Package ID not yet discovered for '$DisplayName', searching winget..." -Source "WinGetMappings"
# Search winget to discover the actual package ID
$searchResult = Search-WinGetRepository -AppName $DisplayName -Publisher $Publisher -CurrentVersion $CurrentVersion
if ($searchResult.PackageId -and $searchResult.PackageId -ne $null) {
# Update the mapping file with discovered package ID
Update-MappingPackageId -AppName $DisplayName -PackageId $searchResult.PackageId
return $searchResult
}
return $searchResult
}
else {
# Found in local mappings with known packageId - get package info directly
$pkgInfo = Get-WinGetPackageInfo -PackageId $mappedPackageId
if ($pkgInfo) {
return @{
Match = "[Available] - $mappedPackageId"
PackageId = $mappedPackageId
Confidence = "High"
LatestVersion = $pkgInfo.Version
}
}
}
}
# Not found in local mappings - search WinGet repository
return Search-WinGetRepository -AppName $DisplayName -Publisher $Publisher -CurrentVersion $CurrentVersion
}
function Load-Applications {
# Hide empty state
if ($controls['AppsEmptyState']) {
$controls['AppsEmptyState'].Visibility = 'Collapsed'
}
if ($controls['AppsDataGrid']) {
$controls['AppsDataGrid'].ItemsSource = $null
$controls['AppsDataGrid'].Visibility = 'Visible'
}
# Check if authenticated
$authState = Get-AuthenticationState
if (-not $authState.IsAuthenticated) {
$authenticated = Show-AuthenticationPrompt -Message "You must be signed in to view applications.`n`nWould you like to sign in now?"
if (-not $authenticated) {
return
}
}
# Fetch applications using Microsoft Graph (runs synchronously to avoid runspace issues)
try {
Write-LogInfo -Message "Fetching applications from Graph API..." -Source "Applications"
# Fetch ALL applications
$allApps = Invoke-MgGraphRequest -Method GET -Uri "beta/deviceAppManagement/mobileApps" -OutputType PSObject
Write-LogInfo -Message "Found $($allApps.value.Count) total apps" -Source "Applications"
$appsList = [System.Collections.ArrayList]::new()
foreach ($app in $allApps.value) {
# Determine app type from @odata.type
$appType = if ($app.'@odata.type') {
$app.'@odata.type' -replace '#microsoft.graph.', '' -replace 'Application', ''
} else {
'Unknown'
}
# Get version information
$currentVersion = if ($app.displayVersion) { $app.displayVersion } else { "Unknown" }
$appsList.Add([PSCustomObject]@{
id = $app.id
displayName = $app.displayName
publisher = $app.publisher
version = $currentVersion
appType = $appType
storeAlternative = "" # Will be populated by Check-WinGetVersions
upgradeAvailable = "" # Will be populated by Check-WinGetVersions
}) | Out-Null
}
# Store apps list in script scope for later WinGet checking
$script:LoadedApps = $appsList
Write-LogInfo -Message "Loaded $($appsList.Count) applications" -Source "Applications"
# Update UI
if ($controls['AppsDataGrid']) {
$controls['AppsDataGrid'].ItemsSource = $appsList
}
# Enable Check Versions button
if ($controls['CheckVersionsButton']) {
$controls['CheckVersionsButton'].IsEnabled = $true
}
}
catch {
Write-LogError -Message "Failed to load applications: $($_.Exception.Message)" -Source "Applications"
[System.Windows.MessageBox]::Show("Failed to load applications:`n$($_.Exception.Message)", "Error", [System.Windows.MessageBoxButton]::OK, [System.Windows.MessageBoxImage]::Error)
}
}
function Check-WinGetVersions {
if (-not $script:LoadedApps -or $script:LoadedApps.Count -eq 0) {
[System.Windows.MessageBox]::Show("Please load applications first.", "Check Versions", [System.Windows.MessageBoxButton]::OK, [System.Windows.MessageBoxImage]::Information)
return
}
# Show progress card
if ($controls['AppsProgressCard']) {
$controls['AppsProgressCard'].Visibility = 'Visible'
}
if ($controls['AppsProgressBar']) {
$controls['AppsProgressBar'].Value = 0
}
if ($controls['AppsProgressText']) {
$controls['AppsProgressText'].Text = "Preparing to check versions..."
}
# Force UI update
$window.Dispatcher.Invoke([Action]{}, [System.Windows.Threading.DispatcherPriority]::Render)
# Disable the button during processing
if ($controls['CheckVersionsButton']) {
$controls['CheckVersionsButton'].IsEnabled = $false
}
# Force UI update
$Window.Dispatcher.Invoke([Action]{}, "Render")
try {
Write-LogInfo -Message "Starting WinGet version check for $($script:LoadedApps.Count) apps..." -Source "Applications"
# Get WinGet apps from the loaded list
$wingetApps = $script:LoadedApps | Where-Object { $_.appType -eq 'winGetApp' }
$checkedCount = 0
$totalCount = $script:LoadedApps.Count
foreach ($app in $script:LoadedApps) {
$checkedCount++
# Calculate progress percentage
$progressPercent = [math]::Round(($checkedCount / $totalCount) * 100)
# Update progress bar and text
if ($controls['AppsProgressBar']) {
$controls['AppsProgressBar'].Value = $progressPercent
}
if ($controls['AppsProgressText']) {
$controls['AppsProgressText'].Text = "Checking $checkedCount of $totalCount apps: $($app.displayName)"
}
# Force UI to update every 5 apps to show progress
if ($checkedCount % 5 -eq 0) {
$Window.Dispatcher.Invoke([Action]{}, "Render")
}
# Check for Store alternative (only for Win32 apps)
if ($app.appType -eq 'win32LobApp') {
$match = Find-StoreAlternative -DisplayName $app.displayName -Publisher $app.publisher -CurrentVersion $app.version -WinGetApps $wingetApps
$app.storeAlternative = $match.Match
# Check if upgrade is available
if ($match.LatestVersion) {
$app.upgradeAvailable = Compare-AppVersion -CurrentVersion $app.version -LatestVersion $match.LatestVersion
}
}
elseif ($app.appType -eq 'winGetApp') {
$app.storeAlternative = "[Store App]"
$app.upgradeAvailable = "Managed by Store"
}
else {
$app.storeAlternative = "N/A"
}
# Refresh DataGrid every 10 apps to show partial results
if ($checkedCount % 10 -eq 0) {
if ($controls['AppsDataGrid']) {
$controls['AppsDataGrid'].Items.Refresh()
}
}
}
Write-LogInfo -Message "Completed WinGet version check" -Source "Applications"
# Final refresh of the DataGrid
if ($controls['AppsDataGrid']) {
$controls['AppsDataGrid'].Items.Refresh()
}
# Hide progress card
if ($controls['AppsProgressCard']) {
$controls['AppsProgressCard'].Visibility = 'Collapsed'
}
[System.Windows.MessageBox]::Show("Completed checking versions for $totalCount applications.", "Version Check Complete", [System.Windows.MessageBoxButton]::OK, [System.Windows.MessageBoxImage]::Information)
}
catch {
Write-LogError -Message "Failed to check versions: $($_.Exception.Message)" -Source "Applications"
# Hide progress card
if ($controls['AppsProgressCard']) {
$controls['AppsProgressCard'].Visibility = 'Collapsed'
}
[System.Windows.MessageBox]::Show("Failed to check versions:`n$($_.Exception.Message)", "Error", [System.Windows.MessageBoxButton]::OK, [System.Windows.MessageBoxImage]::Error)
}
finally {
# Re-enable the button
if ($controls['CheckVersionsButton']) {
$controls['CheckVersionsButton'].IsEnabled = $true
}
}
}
function Export-Applications {
# Get the current data from the DataGrid