-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDeviceAudit.ps1
More file actions
6784 lines (6068 loc) · 287 KB
/
Copy pathDeviceAudit.ps1
File metadata and controls
6784 lines (6068 loc) · 287 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
#####################################################################
### Load Variables from external file
### Make sure you setup your variables in the "Config Files/" folder
### Copy the template.ps1 file or another companies file and create a new one for the new company
### Set the companies config file to use below
. "$PSScriptRoot\Config Files\Global-Config.ps1" # Global Config
. "$PSScriptRoot\Config Files\APIKeys.ps1" # API Keys
. "$PSScriptRoot\Config Files\Config-CCL.ps1" # Company config (CHANGE THIS)
#####################################################################
# This line allows popup boxes to work
Add-Type -AssemblyName PresentationFramework
Write-Host "Computer audit starting..."
$CurrentTLS = [System.Net.ServicePointManager]::SecurityProtocol
if ($CurrentTLS -notlike "*Tls12" -and $CurrentTLS -notlike "*Tls13") {
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
Write-Host "This device is using an old version of TLS. Temporarily changed to use TLS v1.2."
}
# Import/Install any required modules
If (Get-Module -ListAvailable -Name "ImportExcel") {Import-module ImportExcel} Else { install-module ImportExcel -Force; import-module ImportExcel}
If (Get-Module -ListAvailable -Name "Az.Accounts") {Import-module Az.Accounts } Else { install-module Az.Accounts -Force; import-module Az.Accounts }
If (Get-Module -ListAvailable -Name "Az.Resources") {Import-module Az.Resources } Else { install-module Az.Resources -Force; import-module Az.Resources }
If (Get-Module -ListAvailable -Name "Microsoft.Graph.Authentication") {Import-module Microsoft.Graph.Authentication -Force} Else { install-module Microsoft.Graph -Force; import-module Microsoft.Graph.Authentication -Force}
If (Get-Module -ListAvailable -Name "Microsoft.Graph.Identity.DirectoryManagement") {Import-module Microsoft.Graph.Identity.DirectoryManagement -Force}
If (Get-Module -ListAvailable -Name "Microsoft.Graph.DeviceManagement") {Import-module Microsoft.Graph.DeviceManagement -Force}
If (Get-Module -ListAvailable -Name "CosmosDB") {Import-module CosmosDB -MinimumVersion 5.0.0 } Else { install-module CosmosDB -MinimumVersion 5.0.0 -Force; import-module CosmosDB -MinimumVersion 5.0.0 }
If (Get-Module -ListAvailable -Name "ITGlueAPI") {Import-module ITGlueAPI -Force} Else { install-module ITGlueAPI -Force; import-module ITGlueAPI -Force}
If (Get-Module -ListAvailable -Name "AutotaskAPI") {Import-module AutotaskAPI -Force} Else { install-module AutotaskAPI -Force; import-module AutotaskAPI -Force}
If (Get-Module -ListAvailable -Name "JumpCloud") {Import-module JumpCloud -Force} Else { install-module JumpCloud -Force; import-module JumpCloud -Force}
If (Get-Module -ListAvailable -Name "Subnet") {Import-module Subnet -Force} Else { install-module Subnet -Force; import-module Subnet -Force}
# The user audit requires CosmosDB 0.0.1 (a custom version), but the Device Audit requires version 5 or greater
# This makes sure we are running version 5+ without removing the custom version for the User Audit
$CosmosDBModules = Get-Module -ListAvailable -Name "CosmosDB"
$HasNewCosmosDBModule = $false
foreach ($Module in $CosmosDBModules) {
if ($Module.Version.Major -lt 5 -and $Module.Version.Major -gt 0) {
Remove-Module CosmosDB
Uninstall-Module CosmosDB -RequiredVersion $Module.Version
} elseif ($Module.Version.Major -ge 5) {
$HasNewCosmosDBModule = $true
}
}
if (!$HasNewCosmosDBModule) {
Install-Module -Name CosmosDB -MinimumVersion 5.0.0 -Force
}
Import-Module CosmosDB -MinimumVersion 5.0.0 -Force
if ($Ninite_Login.MFA_Secret) {
Unblock-File -Path "$PSScriptRoot\GoogleAuthenticator.psm1"
Import-Module "$PSScriptRoot\GoogleAuthenticator.psm1"
}
# Connect to Azure (with multi-tenant app)
$AzureCredentials = New-Object System.Management.Automation.PSCredential -ArgumentList ($AzureAppCredentials_AllTenants.AppID, (ConvertTo-SecureString $AzureAppCredentials_AllTenants.ClientSecret -AsPlainText -Force))
Connect-AzAccount -ServicePrincipal -Credential $AzureCredentials -Tenant $AzureAppCredentials_AllTenants.TenantID
# Setup CosmosDB app credentials for later
if ($AzureAppCredentials_CosmosDB) {
$AzureCredentials_CosmosDB = New-Object System.Management.Automation.PSCredential -ArgumentList ($AzureAppCredentials_CosmosDB.AppID, (ConvertTo-SecureString $AzureAppCredentials_CosmosDB.ClientSecret -AsPlainText -Force))
}
$DeviceAuditSpreadsheetsUpdated = $false
# Get CPU data and Download new CPU data if older than 2 weeks
if ($CPUDataLocation -and (Test-Path -Path ($CPUDataLocation + "\lastUpdated.txt"))) {
$CPUDataLastUpdated = Get-Content -Path ($CPUDataLocation + "\lastUpdated.txt") -Raw
if ([string]$CPUDataLastUpdated -as [DateTime]) {
$CPUDataLastUpdated = Get-Date $CPUDataLastUpdated
} else {
$CPUDataLastUpdated = $false
}
}
if ($CPUDataLocation -and (Test-Path -Path ($CPUDataLocation + "\cpus.json"))) {
$CPUDetails = Get-Content -Path ($CPUDataLocation + "\cpus.json") -Raw | ConvertFrom-Json
} else {
$CPUDetails = @()
}
if ($CPUDataLocation -and (Test-Path -Path ($CPUDataLocation + "\cpu_matching.json"))) {
$CPUMatching = Get-Content -Path ($CPUDataLocation + "\cpu_matching.json") -Raw | ConvertFrom-Json
} else {
$CPUMatching = @()
}
if ($CPUDataLastUpdated -and $CPUDataLastUpdated.AddDays(14) -lt (Get-Date)) {
$NewCPUList = [System.Collections.ArrayList]@()
$UpdateSuccessful = $true
$headers=@{}
$headers.Add("X-RapidAPI-Host", $RapidAPI_Creds.Host)
$headers.Add("X-RapidAPI-Key", $RapidAPI_Creds.Key)
foreach ($CPUName in $CPUNameSearch) {
try {
$response = Invoke-RestMethod -Uri "https://$($RapidAPI_Creds.Host)/cpus/search/?name=$($CPUName)" -Method GET -Headers $headers
} catch {
if ($_.Exception.Response.StatusCode.value__ -eq 503) {
$UpdateSuccessful = $false
break;
}
}
$response | Foreach-Object { $NewCPUList.Add($_) } | Out-Null
Start-Sleep -Seconds 2 # we are rate limited to 1 call per second
}
if ($UpdateSuccessful -or ($NewCPUList | Measure-Object).Count -gt 0) {
(Get-Date).ToString() | Out-File -FilePath ($CPUDataLocation + "\lastUpdated.txt")
if ($CPUDetails -and $CPUDetails.ID) {
$CPUDetails = [System.Collections.ArrayList]@($CPUDetails)
foreach ($NewCPU in $NewCPUList) {
if ($NewCPU.ID -in $CPUDetails.ID) {
$OldCPUEntry = $CPUDetails | Where-Object { $_.ID -eq $NewCPU.ID }
if ($OldCPUEntry.CPUMark -ne $NewCPU.CPUMark) {
($CPUDetails | Where-Object { $_.ID -eq $NewCPU.ID }).CPUMark = $NewCPU.CPUMark
}
} else {
$CPUDetails.Add($NewCPU)
}
}
} else {
$CPUDetails = $NewCPUList
}
$CPUDetails = $CPUDetails | Sort-Object -Unique -Property ID
$CPUDetails | ConvertTo-Json | Out-File -FilePath ($CPUDataLocation + "\cpus.json")
}
}
$CPUDetailsHash = @{}
foreach ($CPU in $CPUDetails) {
$CPUDetailsHash[$CPU.ID] = $CPU
}
# Connect to IT Glue
$ITGConnected = $false
if ($ITGAPIKey.Key) {
Add-ITGlueBaseURI -base_uri $ITGAPIKey.Url
Add-ITGlueAPIKey $ITGAPIKey.Key
$WANFilterID = (Get-ITGlueFlexibleAssetTypes -filter_name $WANFlexAssetName).data
$LANFilterID = (Get-ITGlueFlexibleAssetTypes -filter_name $LANFlexAssetName).data
$OverviewFilterID = (Get-ITGlueFlexibleAssetTypes -filter_name $OverviewFlexAssetName).data
$ITGConnected = $true
if (!$WANFilterID -or !$LANFilterID -or !$OverviewFilterID) {
Write-Error "Could not get all of the flex asset filter id's from ITG. Exiting..."
exit 1
}
}
# Connect to Autotask
$AutotaskConnected = $false
if ($AutotaskAPIKey.Key) {
$Secret = ConvertTo-SecureString $AutotaskAPIKey.Key -AsPlainText -Force
$Creds = New-Object System.Management.Automation.PSCredential($AutotaskAPIKey.Username, $Secret)
Add-AutotaskAPIAuth -ApiIntegrationcode $AutotaskAPIKey.IntegrationCode -credentials $Creds
Add-AutotaskBaseURI -BaseURI $AutotaskAPIKey.Url
# Verify the Autotask API key works
$AutotaskConnected = $true
try {
Get-AutotaskAPIResource -Resource Companies -ID 0 -ErrorAction Stop
} catch {
$CleanError = ($_ -split "/n")[0]
if ($_ -like "*(401) Unauthorized*") {
$CleanError = "API Key Unauthorized. ($($CleanError))"
}
Write-Host $CleanError -ForegroundColor Red
Write-Error $CleanError
$AutotaskConnected = $false
}
}
# Connect to Microsoft Graph (for Azure/Intune)
$AzureConnected = $false
if ($AzureAppCredentials_AllTenants -and $Azure_TenantID) {
$AuthBody = @{
grant_type = "client_credentials"
scope = "https://graph.microsoft.com/.default"
client_id = $AzureAppCredentials_AllTenants.AppID
client_secret = $AzureAppCredentials_AllTenants.ClientSecret
}
$conn = Invoke-RestMethod `
-Uri "https://login.microsoftonline.com/$Azure_TenantID/oauth2/v2.0/token" `
-Method POST `
-Body $AuthBody
$AzureToken = ConvertTo-SecureString -String $conn.access_token -AsPlainText -Force
$MgGraphConnect = Connect-MgGraph -AccessToken $AzureToken
if ($MgGraphConnect -like "Welcome To Microsoft Graph!*") {
$AzureConnected = $true
}
}
# Connect to JumpCloud (if applicable)
$JCConnected = $false
if ($JumpCloudAPIKey -and $JumpCloudAPIKey.Key) {
Connect-JCOnline -JumpCloudApiKey $JumpCloudAPIKey.Key
$JCConnected = $true
}
# Authenticate with Ninite
$NiniteAuthResponse = $false
if ($Ninite_Login.Email) {
# Get the xsrf token from the form
$NiniteSignInPage = Invoke-WebRequest "$($Ninite_Login.BaseURI)signin/" -SessionVariable 'NiniteWebSession' -UseBasicParsing
$XSRFToken = ($NiniteSignInPage.InputFields | Where-Object { $_.name -eq "_xsrf" }).value
if ($XSRFToken) {
# Attempt initial login
$FormBody = @{
email = $Ninite_Login.Email
pw = $Ninite_Login.Password
"_xsrf" = $XSRFToken
}
try {
$NiniteAuthResponse = Invoke-WebRequest "$($Ninite_Login.BaseURI)signin/" -UseBasicParsing -WebSession $NiniteWebSession -Body $FormBody -Method 'POST' -ContentType 'application/x-www-form-urlencoded'
} catch {
Write-Warning "Failed to connect to: Ninite"
Write-Host "Status Code: $($_.Exception.Response.StatusCode.Value__)"
Write-Host "Message: $($_.Exception.Message)"
Write-Host "Status Description: $($_.Exception.Response.StatusDescription)"
}
}
if ($NiniteAuthResponse.Content -like "*Please enter the current two-factor code*") {
if ($Ninite_Login.MFA_Secret -and $Ninite_Login.MFA_Method -eq "totp") {
$MFACode = Get-GoogleAuthenticatorPin -Secret $Ninite_Login.MFA_Secret
if ($MFACode.'Seconds Remaining' -le 5) {
# If the current code is about to expire, lets wait until a new one is ready to be generated to grab the code and try to login
Start-Sleep -Seconds ($MFACode.'Seconds Remaining' + 1)
$MFACode = Get-GoogleAuthenticatorPin -Secret $Ninite_Login.MFA_Secret
}
$FormBody = @{
totp = $MFACode."PIN Code" -replace " ", ""
method = "totp"
"_xsrf" = $XSRFToken
}
try {
$NiniteAuthResponse = Invoke-WebRequest "$($Ninite_Login.BaseURI)me/2fa/challenge" -UseBasicParsing -WebSession $NiniteWebSession -Body $FormBody -Method 'POST' -ContentType 'application/x-www-form-urlencoded'
} catch {
Write-Warning "Failed to connect to: Ninite"
Write-Host "Status Code: $($_.Exception.Response.StatusCode.Value__)"
Write-Host "Message: $($_.Exception.Message)"
Write-Host "Status Description: $($_.Exception.Response.StatusDescription)"
}
} elseif (!$Ninite_Login.MFA_Secret) {
Write-Warning "An MFA secret is required for the Ninite login. Could not authenticate. Please verify the credentials and try again."
} elseif ($Ninite_Login.MFA_Method -ne "totp") {
Write-Warning "Please setup Ninite with the TOTP MFA type. This script does not support other versions of MFA."
}
}
if (!$NiniteAuthResponse) {
Write-Warning "Failed to connect to: Ninite"
}
}
# Get all devices from RMM
$RMM_Devices = @()
if ($RMM_ID) {
If (Get-Module -ListAvailable -Name "DattoRMM") {Import-module DattoRMM -Force} Else { install-module DattoRMM -Force; import-module DattoRMM -Force}
Set-DrmmApiParameters -Url $DattoAPIKey.URL -Key $DattoAPIKey.Key -SecretKey $DattoAPIKey.SecretKey
if ($RMM_ID -match "^\d+$") {
$CompanyInfo = Get-DrmmAccountSites | Where-Object { $_.id -eq $RMM_ID }
$RMM_ID = $CompanyInfo.uid
}
$RMM_Devices = Get-DrmmSiteDevices $RMM_ID | Where-Object { $_.deviceClass -eq 'device' -and $_.deviceType.category -in @("Laptop", "Desktop", "Server") }
}
# Get all devices from ITG
$ITG_Devices = @()
if ($ITGConnected -and $ITG_ID) {
$ITG_Devices = Get-ITGlueConfigurations -page_size "1000" -organization_id $ITG_ID
$i = 1
while ($ITG_Devices.links.next) {
$i++
$Configurations_Next = Get-ITGlueConfigurations -page_size "1000" -page_number $i -organization_id $ITG_ID
if (!$Configurations_Next -or $Configurations_Next.Error) {
# We got an error querying configurations, wait and try again
Start-Sleep -Seconds 2
$Configurations_Next = Get-ITGlueConfigurations -page_size "1000" -page_number $i -organization_id $ITG_ID
if (!$Configurations_Next -or $Configurations_Next.Error) {
Write-Error "An error occurred trying to get the existing configurations from ITG. Exiting..."
Write-Error $Configurations_Next.Error
exit 1
}
}
$ITG_Devices.data += $Configurations_Next.data
$ITG_Devices.links = $Configurations_Next.links
}
if ($ITG_Devices -and $ITG_Devices.data) {
$ITG_Devices = $ITG_Devices.data
}
if (!$ITG_Devices) {
Write-Warning "There was an issue getting the Configurations from ITG. Exiting..."
exit 1
}
}
$ITG_DevicesHash = @{}
foreach ($Device in $ITG_Devices) {
$ITG_DevicesHash[$Device.id] = $Device
}
# Get all devices from Autotask + locations & contacts for spreadsheet exports
$Autotask_Devices = @()
if ($AutotaskConnected -and $Autotask_ID) {
$Autotask_Devices = Get-AutotaskAPIResource -Resource ConfigurationItems -SimpleSearch "companyID eq $Autotask_ID"
$Autotask_Devices = $Autotask_Devices | Where-Object { $_.isActive -eq "True" }
$Autotask_Locations = Get-AutotaskAPIResource -Resource CompanyLocations -SimpleSearch "companyID eq $Autotask_ID"
$Autotask_Locations = $Autotask_Locations | Where-Object { $_.isActive -eq "True" }
$DefaultAutotaskLocation = $Autotask_Locations | Where-Object { $_.isPrimary -eq "True" } | Select-Object -First 1
$Autotask_Contacts = Get-AutotaskAPIResource -Resource Contacts -SimpleSearch "companyID eq $Autotask_ID"
$Autotask_Contacts = $Autotask_Contacts | Where-Object { $_.isActive -eq 1 }
# $Autotask_Contracts = Get-AutotaskAPIResource -Resource Contracts -SimpleSearch "companyID eq $Autotask_ID"
# $Autotask_Contract = $Autotask_Contracts | Where-Object { $_.isDefaultContract -eq "True" }
}
$Autotask_DevicesHash = @{}
foreach ($Device in $Autotask_Devices) {
$Autotask_DevicesHash[$Device.id] = $Device
}
# Get all devices from Azure & Intune
$Azure_Devices = @()
$Intune_Devices = @()
if ($AzureConnected) {
$Azure_Devices = Get-MgDevice -All | Where-Object { $_.OperatingSystem -notin @("Android", "iOS") }
$Intune_Devices = Get-MgDeviceManagementManagedDevice | Where-Object { $_.OperatingSystem -notin @("Android", "iOS") }
}
$Azure_DevicesHash = @{}
$Intune_DevicesHash = @{}
foreach ($Device in $Azure_Devices) {
$Azure_DevicesHash[$Device.id] = $Device
}
foreach ($Device in $Intune_Devices) {
$Intune_DevicesHash[$Device.Id] = $Device
}
# Get all devices from JumpCloud
$JC_Devices = @()
if ($JCConnected) {
$JC_Devices = Get-JCSystem | Where-Object { $_.desktopCapable }
}
$JC_DevicesHash = @{}
foreach ($Device in $JC_Devices) {
$JC_DevicesHash[$Device.id] = $Device
}
# Get all devices from SC
# Send a post request to $SCLogin.URL/Services/AuthenticationService.ashx/TryLogin
# to set the login cookie
$Nonce = $SC_Nonce # Manually obtained from SC.util.getRandomAlphanumericString(16); (it just seems to care that the format is correct)
$FormBody = @(
$SCLogin.Username,
$SCLogin.Password,
$false,
$false,
$Nonce
) | ConvertTo-Json
$Response = Invoke-WebRequest "$($SCLogin.URL)/Services/AuthenticationService.ashx/TryLogin" -UseBasicParsing -SessionVariable 'SCWebSession' -Body $FormBody -Method 'POST' -ContentType 'application/json'
# Download the full device list report and then import it
$Response = Invoke-WebRequest "$($SCLogin.URL)/Report.csv?ReportType=Session&SelectFields=SessionID&SelectFields=Name&SelectFields=GuestMachineName&SelectFields=GuestMachineSerialNumber&SelectFields=GuestHardwareNetworkAddress&SelectFields=GuestOperatingSystemName&SelectFields=GuestLastActivityTime&SelectFields=GuestInfoUpdateTime&SelectFields=GuestLastBootTime&SelectFields=GuestLoggedOnUserName&SelectFields=GuestLoggedOnUserDomain&SelectFields=GuestMachineManufacturerName&SelectFields=GuestMachineModel&SelectFields=GuestMachineDescription&SelectFields=CustomProperty1&SelectFields=GuestSystemMemoryTotalMegabytes&SelectFields=GuestProcessorName&SelectFields=GuestProcessorVirtualCount&Filter=SessionType%20%3D%20'Access'%20AND%20NOT%20IsEnded&AggregateFilter=&ItemLimit=100000" -UseBasicParsing -WebSession $SCWebSession
$SC_Devices = $Response.Content | ConvertFrom-Csv
# Function to convert imported UTC date/times to local time for easier comparisons
function Convert-UTCtoLocal {
param( [parameter(Mandatory=$true)] [String] $UTCTime )
$strCurrentTimeZone = (Get-WmiObject win32_timezone).StandardName
$TZ = [System.TimeZoneInfo]::FindSystemTimeZoneById($strCurrentTimeZone)
$LocalTime = [System.TimeZoneInfo]::ConvertTimeFromUtc($UTCTime, $TZ)
return $LocalTime
}
############
# Connect to the Sophos API to get the device list from Sophos
############
# Get token
$SophosTenantID = $false
$Body = @{
grant_type = "client_credentials"
client_id = $SophosAPIKey.ClientID
client_secret = $SophosAPIKey.Secret
scope = "token"
}
$SophosToken = Invoke-RestMethod -Method POST -Body $Body -ContentType "application/x-www-form-urlencoded" -uri "https://id.sophos.com/api/v2/oauth2/token"
$SophosJWT = $SophosToken.access_token
$SophosToken | Add-Member -NotePropertyName expiry -NotePropertyValue $null
$SophosToken.expiry = (Get-Date).AddSeconds($SophosToken.expires_in - 60)
if ($SophosJWT) {
# Get our partner ID
$SophosHeader = @{
Authorization = "Bearer $SophosJWT"
}
$SophosPartnerInfo = Invoke-RestMethod -Method GET -Headers $SophosHeader -uri "https://api.central.sophos.com/whoami/v1"
$SophosPartnerID = $SophosPartnerInfo.id
if ($SophosPartnerID) {
# Get list of tenants, so we can get the companies ID in sophos
$SophosHeader = @{
Authorization = "Bearer $SophosJWT"
"X-Partner-ID" = $SophosPartnerID
}
$SophosTenants = Invoke-RestMethod -Method GET -Headers $SophosHeader -uri "https://api.central.sophos.com/partner/v1/tenants?pageTotal=true"
if ($SophosTenants.pages -and $SophosTenants.pages.total -gt 1) {
$TotalPages = $SophosTenants.pages.total
for ($i = 2; $i -le $TotalPages; $i++) {
$SophosTenants.items += (Invoke-RestMethod -Method GET -Headers $SophosHeader -uri "https://api.central.sophos.com/partner/v1/tenants?page=$i").items
}
}
# Get the tenants ID and URL
if ($SophosTenants.items -and $Sophos_Company) {
$CompanyInfo = $SophosTenants.items | Where-Object { $_.name -like $Sophos_Company }
$SophosTenantID = $CompanyInfo.id
$TenantApiHost = $CompanyInfo.apiHost
}
}
}
# Finally get the Sophos endpoints
$SophosEndpoints = $false
if ($SophosTenantID -and $TenantApiHost) {
$SophosHeader = @{
Authorization = "Bearer $SophosJWT"
"X-Tenant-ID" = $SophosTenantID
}
$SophosEndpoints = Invoke-RestMethod -Method GET -Headers $SophosHeader -uri ($TenantApiHost + "/endpoint/v1/endpoints?pageSize=500")
$NextKey = $false
if ($SophosEndpoints.pages.nextKey) {
$SophosEndpoints.items = [System.Collections.Generic.List[PSCustomObject]]$SophosEndpoints.items
$NextKey = $SophosEndpoints.pages.nextKey
}
while ($NextKey) {
$SophosEndpoints_NextPage = $false
$SophosEndpoints_NextPage = Invoke-RestMethod -Method GET -Headers $SophosHeader -uri ($TenantApiHost + "/endpoint/v1/endpoints?pageFromKey=$NextKey")
foreach ($Endpoint in $SophosEndpoints_NextPage.items) {
$SophosEndpoints.items.Add($Endpoint)
}
$NextKey = $false
if ($SophosEndpoints_NextPage.pages.nextKey) {
$NextKey = $SophosEndpoints_NextPage.pages.nextKey
}
}
}
if ($SophosEndpoints -and $SophosEndpoints.items) {
$Sophos_Devices = $SophosEndpoints.items | Where-Object { $_.type -eq "computer" -or $_.type -eq "server" }
} else {
$Sophos_Devices = @()
Write-Host "Warning! Could not get device list from Sophos!" -ForegroundColor Red
}
############
# End Sophos device collection
###########
# Get org info and devices from Ninite
$Ninite_Machines = @()
if ($NiniteAuthResponse) {
$NiniteHeader = @{
"x-xsrftoken" = $XSRFToken
"ninite-role" = 0
}
$FormBody = @{
id = 1
jsonrpc = "2.0"
method = "get_org_info"
params = @{}
} | ConvertTo-Json
$NiniteResponse = Invoke-WebRequest "$($Ninite_Login.BaseURI)remote/rpc_web" -UseBasicParsing -WebSession $NiniteWebSession -Headers $NiniteHeader -Body $FormBody -Method 'POST' -ContentType 'application/json; charset=utf-8'
$Ninite_OrgInfo = $NiniteResponse.Content | ConvertFrom-Json
$TotalNiniteDevices = $Ninite_OrgInfo.result.machine_ids.count
for ($i = 0; $i -lt [Math]::Ceiling($TotalNiniteDevices / 500); $i++) {
$StartIndex = $i * 500
$EndIndex = ($i+1) * 500 - 1
$FormBody = @{
id = 1
jsonrpc = "2.0"
method = "get_machines"
params = @{
machine_ids = @($Ninite_OrgInfo.result.machine_ids[$StartIndex..$EndIndex])
}
} | ConvertTo-Json
$NiniteResponse = Invoke-WebRequest "$($Ninite_Login.BaseURI)remote/rpc_web" -UseBasicParsing -WebSession $NiniteWebSession -Headers $NiniteHeader -Body $FormBody -Method 'POST' -ContentType 'application/json; charset=utf-8'
$Ninite_Machines += ($NiniteResponse.Content | ConvertFrom-Json).result
Start-Sleep -Seconds 1
}
}
$Ninite_DevicesHash = @{}
foreach ($Device in $Ninite_Machines) {
$Ninite_DevicesHash[$Device.id] = $Device
}
# Get RMM device details if using the API
if ($RMM_Devices) {
$i = 0
foreach ($Device in $RMM_Devices) {
$i++
[int]$PercentComplete = ($i / $RMM_Devices.count * 100)
Write-Progress -Activity "Getting RMM device details" -PercentComplete $PercentComplete -Status ("Working - " + $PercentComplete + "%")
$Device | Add-Member -NotePropertyName serialNumber -NotePropertyValue $false
$Device | Add-Member -NotePropertyName manufacturer -NotePropertyValue $false
$Device | Add-Member -NotePropertyName model -NotePropertyValue $false
$Device | Add-Member -NotePropertyName MacAddresses -NotePropertyValue @()
$Device | Add-Member -NotePropertyName memory -NotePropertyValue $false
$Device | Add-Member -NotePropertyName cpus -NotePropertyValue $false
$Device | Add-Member -NotePropertyName cpuCores -NotePropertyValue $false
$Device | Add-Member -NotePropertyName url -NotePropertyValue $false
$AuditDevice = Get-DrmmAuditDevice $Device.uid
if ($AuditDevice) {
$Device.serialNumber = $AuditDevice.bios.serialNumber
$Device.manufacturer = $AuditDevice.systemInfo.manufacturer
$Device.model = $AuditDevice.systemInfo.model
$Device.MacAddresses = @($AuditDevice.nics | Select-Object instance, macAddress)
$Device.memory = $AuditDevice.systemInfo.totalPhysicalMemory
$Device.cpus = $AuditDevice.processors
$Device.cpuCores = $AuditDevice.systemInfo.totalCpuCores
$Device.url = $AuditDevice.portalUrl
}
}
Write-Progress -Activity "Getting RMM device details" -Status "Ready" -Completed
}
Write-Host "Imported all devices."
Write-Host "===================="
# Filter Screen Connect Devices
if ($SC_Company.GetType().Name -like "String") {
$SC_Devices = $SC_Devices | Where-Object { $_.CustomProperty1 -like $SC_Company }
} else {
$SC_Devices_Temp = @()
foreach ($Company in $SC_Company) {
$SC_Devices_Temp += $SC_Devices | Where-Object { $_.CustomProperty1 -like $Company }
}
$SC_Devices = $SC_Devices_Temp
}
# Filter columns to only the one's we want
$SC_Devices = $SC_Devices | Select-Object SessionID, Name, GuestMachineName, GuestMachineSerialNumber, GuestHardwareNetworkAddress,
@{Name="DeviceType"; E={if ($_.GuestOperatingSystemName -like "*Server*") { "Server" } else { "Workstation" } }},
@{Name="GuestLastActivityTime"; E={Convert-UTCtoLocal($_.GuestLastActivityTime)}}, @{Name="GuestInfoUpdateTime"; E={Convert-UTCtoLocal($_.GuestInfoUpdateTime)}}, @{Name="GuestLastBootTime"; E={Convert-UTCtoLocal($_.GuestLastBootTime)}},
GuestLoggedOnUserName, GuestLoggedOnUserDomain, GuestOperatingSystemName, GuestMachineManufacturerName, GuestMachineModel, GuestMachineDescription, GuestSystemMemoryTotalMegabytes, GuestProcessorName, GuestProcessorVirtualCount
# Sometimes the LastActivityTime field is not set even though the device is on, in these cases it's set to Year 1
# Also, if a computer is online but inactive, the infoupdate time can be more recent and a better option
# We'll create a new GuestLastSeen property here that is the most recent date of the 3 available
$SC_Devices | Add-Member -NotePropertyName GuestLastSeen -NotePropertyValue $null
$SC_Devices | ForEach-Object {
$MostRecentDate = @($_.GuestLastActivityTime, $_.GuestInfoUpdateTime, $_.GuestLastBootTime) | Sort-Object | Select-Object -Last 1
$_.GuestLastSeen = $MostRecentDate
}
$SC_DevicesHash = @{}
foreach ($Device in $SC_Devices) {
$SC_DevicesHash[$Device.SessionID] = $Device
}
$RMM_Devices = $RMM_Devices |
Select-Object @{Name="Device UID"; E={$_.uid}}, @{Name="Device Hostname"; E={$_.hostname}}, @{Name="Serial Number"; E={$_.serialNumber}}, MacAddresses,
@{Name="Device Type"; E={$_.deviceType.category}}, @{Name="Status"; E={$_.online}}, @{Name="Last Seen"; E={ if ($_.online -eq "True") { Get-Date } else { Convert-UTCtoLocal(([datetime]'1/1/1970').AddMilliseconds($_.lastSeen)) } }},
extIpAddress, intIpAddress,
@{Name="Last User"; E={$_.lastLoggedInUser}}, Domain, @{Name="Operating System"; E={$_.operatingSystem}},
Manufacturer, @{Name="Device Model"; E={$_.model}}, @{Name="Warranty Expiry"; E={$_.warrantyDate}}, @{Name="Device Description"; E={$_.description}},
memory, cpus, cpuCores, url,
@{Name="ScreenConnectID"; E={
$SC = $_.udf.udf13;
if ($SC -and $SC -like "*$($SCLogin.URL.TrimStart('http').TrimStart('s').TrimStart('://'))*") {
$Found = $SC -match '\/\/((\{){0,1}[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}(\}){0,1})\/Join'
if ($Found -and $Matches[1]) {
$Matches[1]
}
}
}}, @{Name="SophosEndpointID"; E={ $_.udf.udf4 }}, @{Name="ToDelete"; E={ if ($_.udf.udf30 -eq "True") { $true } else { $false } }}, suspended,
@{Name="Win11Compatible"; E={ $_.udf.udf15 }}
$RMM_DevicesHash = @{}
foreach ($Device in $RMM_Devices) {
$RMM_DevicesHash[$Device."Device UID"] = $Device
}
$Sophos_Devices = $Sophos_Devices | Select-Object id, @{Name="hostname"; E={$_.hostname -replace '[^\x00-\x7F]+', ''}}, macAddresses,
@{Name="type"; E={if ($_.type -eq "computer") { "Workstation"} else { "Server" }}},
lastSeenAt, @{Name="LastUser"; E={($_.associatedPerson.viaLogin -split '\\')[1]}}, @{Name="OS"; E={if ($_.os.name) { $_.os.name } else { "$($_.os.platform) $($_.os.majorVersion).$($_.os.minorVersion)" }}}
$Sophos_DevicesHash = @{}
foreach ($Device in $Sophos_Devices) {
$Sophos_DevicesHash[$Device.id] = $Device
}
# The id on each Sophos device is not the same ID that is used on the website
# To get this ID, we must invert each pair of characters in the ID
function convert_sophos_id_to_web($EndpointID) {
$WebEndpointID = ""
$Length = $EndpointID.length
for ($i = 0; $i -lt $Length; $i ++) {
if ($EndpointID[$i] -eq "-") {
$WebEndpointID += "-"
continue
}
$WebEndpointID += $EndpointID[$i+1]
$WebEndpointID += $EndpointID[$i]
$i++
}
return $WebEndpointID
}
foreach ($Device in $Sophos_Devices) {
$Device | Add-Member -NotePropertyName webID -NotePropertyValue $false
$EndpointID = $Device.id
$WebEndpointID = convert_sophos_id_to_web $EndpointID
$Device.webID = $WebEndpointID
}
##############
# Matching Section
##############
# This function checks the force match array for any forced matches and returns them
# Input the device ID and the $Type of connection (SC, RMM, Sophos, or ITG)
# Returns an array containing hashtables for each match with the matching connections type, and device id, and if we want to match with this id or ignore this id
# @( @{"type" = "sc, rmm, sophos, or itg", "id" = "device id or $false for no match", "match" = $true if we want to match to this ID, $false if we want to block matches with this id } )
function force_match($DeviceID, $Type) {
$Types = @("SC", "RMM", "Sophos", "ITG")
if (!$Type -or $Type -notin $Types) {
return
}
$ForcedMatches = @()
foreach ($DefaultType in $Types) {
# For each entry in the type we are getting, get all by from id
if ($DefaultType -like $Type) {
foreach ($Match in $ForceMatch.$Type) {
# Check if id matches, if this is a sophos match, see if the inverted id matches as well
if ($Match.from -like $DeviceID -or (($Match.tosystem -like "Sophos" -or $DefaultType -like "Sophos") -and (convert_sophos_id_to_web $Match.from) -like $DeviceID)) {
$ForcedMatches += @{
type = $Match.tosystem
id = $Match.to
match = [bool]$Match.to
}
}
}
# For each entry in other types, get all by to id
} else {
foreach ($Match in $ForceMatch.$DefaultType) {
if ($Match.tosystem -like $Type -and ($Match.to -like $DeviceID -or $Match.to -eq $false -or (($Match.tosystem -like "Sophos" -or $DefaultType -like "Sophos") -and (convert_sophos_id_to_web $Match.to) -like $DeviceID))) {
$ForcedMatches += @{
type = $DefaultType
id = $Match.from
match = [bool]$Match.to
}
}
}
}
}
# Convert and add a new entry for any sophos ids into their web id equivalent as well (sophos uses inverted ids on their website which is most likely what will be entered in the $ForceMatches section)
$ForcedMatchesCopy = $ForcedMatches
foreach ($Match in $ForcedMatchesCopy) {
if ($Match.type -like "Sophos" -and $Match.id) {
$ForcedMatches += @{
type = $Match.type
id = convert_sophos_id_to_web $Match.id
match = $Match.match
}
}
}
return $ForcedMatches
}
# Match devices between the device lists
Write-Host "Matching devices..."
$MatchedDevices = @()
# Match ScreenConnect devices with themselves to find any duplicates
foreach ($Device in $SC_Devices) {
if ($Device.SessionID -in $MatchedDevices.sc_matches) {
continue
}
$Related_SCDevices = @()
$ForcedMatches = force_match -DeviceID $Device.SessionID -Type "SC"
$ForcedMatches = $ForcedMatches | Where-Object { $_.type -like 'sc' }
# Check for force matches first
if ($ForcedMatches) {
# Match IDs
foreach ($Match in ($ForcedMatches | Where-Object { $_.id -ne $false })) {
$Related_SCDevices += $SC_DevicesHash[$Match.id]
}
# If $ForcedMatches contains the id = $false, stop checking for duplicates
if ((($ForcedMatches | Where-Object { $_.id -eq $false }) | Measure-Object).Count -gt 0) {
Continue
}
}
$Related_SCDevices += @($SC_Devices | Where-Object {
$Device.SessionID -notlike $_.SessionID -and (
($Device.GuestMachineSerialNumber.Trim() -and $Device.GuestMachineSerialNumber -notin $IgnoreSerials -and $Device.GuestMachineSerialNumber -notlike "123456789*" -and $_.GuestMachineSerialNumber -like $Device.GuestMachineSerialNumber) -or
($Device.Name.Trim() -and ($_.Name -eq $Device.Name -or $_.GuestMachineName -eq $Device.Name) -and ($_.GuestMachineSerialNumber -like $Device.GuestMachineSerialNumber -or $_.GuestHardwareNetworkAddress -eq $Device.GuestHardwareNetworkAddress)) -or
($Device.GuestMachineName.Trim() -and ($_.GuestMachineName -eq $Device.GuestMachineName -or $_.Name -eq $Device.GuestMachineName) -and ($_.GuestMachineSerialNumber -like $Device.GuestMachineSerialNumber -or $_.GuestHardwareNetworkAddress -eq $Device.GuestHardwareNetworkAddress))
)
})
# Get mac address matches only separately, then see if we can cross-reference them with RMM and ignore any that are from USB network adapters
$MacRelated_SCDevices = @($SC_Devices | Where-Object {
$Device.SessionID -notlike $_.SessionID -and (
($Device.GuestHardwareNetworkAddress -and $_.GuestHardwareNetworkAddress -eq $Device.GuestHardwareNetworkAddress -and $Device.GuestMachineModel -notlike "Virtual Machine")
)
})
$MacRelated_SCDevices = $MacRelated_SCDevices | Where-Object {
$Related_RMMDeviceMacs = $RMM_Devices.MacAddresses | Where-Object { $_.macAddress -like $Device.GuestHardwareNetworkAddress }
if (($Related_RMMDeviceMacs | Measure-Object).Count -gt 0 -and $Related_RMMDeviceMacs.instance -notlike "*USB*" -and $Related_RMMDeviceMacs.instance -notlike "*Ethernet Adapter*" -and $ConnectedMac.instance -like "*Plugable Ethernet*") {
$_
return
}
}
if (($MacRelated_SCDevices | Measure-Object).Count -gt 0) {
$Related_SCDevices += $MacRelated_SCDevices
}
$Related_SCDevices = @($Related_SCDevices | Sort-Object SessionID -Unique)
if (($Related_SCDevices | Measure-Object).Count -gt 0) {
$Related_SCDevices += $Device
$MatchedDevices += [PsCustomObject]@{
id = New-Guid
sc_matches = @($Related_SCDevices.SessionID)
sc_hostname = @($Related_SCDevices.Name)
rmm_matches = @()
rmm_hostname = @()
sophos_matches = @()
sophos_hostname = @()
itg_matches = @()
itg_hostname = @()
autotask_matches = @()
autotask_hostname = @()
jc_matches = @()
jc_hostname = @()
azure_matches = @()
azure_hostname = @()
azure_match_warning = @()
intune_matches = @()
intune_hostname = @()
ninite_matches = @()
ninite_hostname = @()
}
} else {
$MatchedDevices += [PsCustomObject]@{
id = New-Guid
sc_matches = @($Device.SessionID)
sc_hostname = @($Device.Name)
rmm_matches = @()
rmm_hostname = @()
sophos_matches = @()
sophos_hostname = @()
itg_matches = @()
itg_hostname = @()
autotask_matches = @()
autotask_hostname = @()
jc_matches = @()
jc_hostname = @()
azure_matches = @()
azure_hostname = @()
azure_match_warning = @()
intune_matches = @()
intune_hostname = @()
ninite_matches = @()
ninite_hostname = @()
}
}
}
# Match ScreenConnect devices to RMM
foreach ($MatchedDevice in $MatchedDevices) {
$Matched_SC_Devices = @()
foreach ($DeviceID in $MatchedDevice.sc_matches) {
$Matched_SC_Devices += $SC_DevicesHash[$DeviceID]
}
foreach ($Device in $Matched_SC_Devices) {
$Related_RMMDevices = @()
$ForcedMatches = force_match -DeviceID $Device.SessionID -Type "SC"
$ForcedMatches = $ForcedMatches | Where-Object { $_.type -like 'rmm' }
$IgnoreRMM = @(($ForcedMatches | Where-Object { $_.match -eq $false }).id)
$ForcedMatches = @($ForcedMatches | Where-Object { $_.id -ne $false -and $_.match -ne $false })
while (!$Related_RMMDevices) {
# Forced matches
if ($ForcedMatches) {
# Match IDs
foreach ($Match in $ForcedMatches) {
$Related_RMMDevices += $RMM_DevicesHash[$Match.id]
}
}
# If $IgnoreRMM contains $False, stop here as that means we dont want to match with any more rmm devices
if ($IgnoreRMM -contains $false) {
break;
}
# Remove false entries in $IgnoreRMM now so we can easily check against the list of IDs
$IgnoreRMM = @($IgnoreRMM | Where-Object { $_ })
# Screen connect session ID
$Related_RMMDevices += $RMM_Devices | Where-Object { $_.ScreenConnectID -like $Device.SessionID -and $_."Device UID" -notin $IgnoreRMM }
# Serial number
if ($Device.GuestMachineSerialNumber.Trim() -and $Device.GuestMachineSerialNumber -notin $IgnoreSerials -and $Device.GuestMachineSerialNumber -notlike "123456789*") {
$Related_RMMDevices += $RMM_Devices | Where-Object { $_."Serial Number" -like $Device.GuestMachineSerialNumber -and $_."Device UID" -notin $IgnoreRMM }
}
# Hostname
if ($Device.Name.Trim() -and ($Device.GuestOperatingSystemName -notlike "*Mac OS*" -or ($Device.Name -replace "[^0-9]" , '' | Measure-Object -Character).Characters -gt 2)) {
$Related_RMMDevices += $RMM_Devices | Where-Object { $_."Device Hostname" -eq $Device.Name -and $_."Device UID" -notin $IgnoreRMM }
}
if ($Device.GuestMachineName.Trim() -and ($Device.GuestOperatingSystemName -notlike "*Mac OS*" -or ($Device.GuestMachineName -replace "[^0-9]" , '' | Measure-Object -Character).Characters -gt 2)) {
$Related_RMMDevices += $RMM_Devices | Where-Object { $_."Device Hostname" -eq $Device.GuestMachineName -and $_."Device UID" -notin $IgnoreRMM }
}
# Mac address (if this is a VM, only check this if we haven't found any related devices so far. VM's can cause false positives with this search.)
if ($Device.GuestHardwareNetworkAddress -and (!$Related_RMMDevices -or $Device.GuestMachineModel -notlike "Virtual Machine")) {
$MacRelated_RMMDevices = $RMM_Devices | Where-Object { $_.MacAddresses.macAddress -contains $Device.GuestHardwareNetworkAddress -and $_."Device UID" -notin $IgnoreRMM }
if ($MacRelated_RMMDevices.MacAddresses.instance) {
$MacRelated_RMMDevices = $MacRelated_RMMDevices | Where-Object {
# Remove any usb adapter mac matches unless the hostname also matches
$ConnectedMac = $_.MacAddresses | Where-Object { $_.macAddress -like $Device.GuestHardwareNetworkAddress }
if (($ConnectedMac.instance -like "*USB*" -or $ConnectedMac.instance -like "*Ethernet Adapter*" -or $ConnectedMac.instance -like "*Plugable Ethernet*" -or $ConnectedMac.instance -like "*Modem Mobile Broadband Device*") -and $Device.Name -notlike $_."Device Hostname" -and $Device.GuestMachineName -notlike $_."Device Hostname") {
$false
return
} else {
$_
return
}
}
}
$Related_RMMDevices += $MacRelated_RMMDevices
}
# Description searches as a backup
if (!$Related_RMMDevices) {
if ($Device.Name.Trim()) {
$EscapedName = $Device.Name.replace("[", "````[").replace("]", "````]")
if ($EscapedName -notlike "MacBook-Pro*") {
$Related_RMMDevices += $RMM_Devices | Where-Object { $_."Device Description" -like "*$($EscapedName)*" -and $_."Device UID" -notin $IgnoreRMM }
}
}
if ($Device.GuestMachineName.Trim()) {
$EscapedName2 = $Device.GuestMachineName.replace("[", "````[").replace("]", "````]")
if ($EscapedName2 -notlike "MacBook-Pro*") {
$Related_RMMDevices += $RMM_Devices | Where-Object { $_."Device Description" -like "*$($EscapedName2)*" -and $_."Device UID" -notin $IgnoreRMM }
}
}
if (($Related_RMMDevices | Measure-Object).Count -gt 4) {
# Sanity check in case the name of the device is a little too generic and we get a ton of matches
$Related_RMMDevices = @()
}
}
if (!$Related_RMMDevices -and $Device.GuestMachineDescription.Trim() -and $Device.GuestMachineDescription.length -gt 5 -and $Device.GuestMachineDescription -like "*-*" -and $Device.GuestMachineDescription.Trim() -notlike "* *") {
$Related_RMMDevices += $RMM_Devices | Where-Object { $_."Device Description" -like "*$($Device.GuestMachineDescription.Trim())*" -and $_."Device UID" -notin $IgnoreRMM }
}
$Related_RMMDevices = $Related_RMMDevices | Sort-Object "Device UID" -Unique
break;
}
# If there was more than 1 related device found, try to filter the results down (particularly matches found on hostname)
if (($Related_RMMDevices | Measure-Object).Count -gt 1) {
$Related_RMMDevices_Filtered = $Related_RMMDevices | Where-Object {
$_.ScreenConnectID -like $Device.SessionID -or
($Device.GuestMachineSerialNumber.Trim() -and $Device.GuestMachineSerialNumber -notin $IgnoreSerials -and $Device.GuestMachineSerialNumber -notlike "123456789*" -and $_."Serial Number" -like $Device.GuestMachineSerialNumber) -or
($Device.GuestHardwareNetworkAddress -and $_.MacAddresses.macAddress -contains $Device.GuestHardwareNetworkAddress -and $Device.GuestMachineModel -notlike "Virtual Machine") -or
($Device.Name.Trim() -and $_."Device Hostname" -eq $Device.Name -and ($_."Serial Number" -like $Device.GuestMachineSerialNumber -or $_.MacAddresses.macAddress -contains $Device.GuestHardwareNetworkAddress)) -or
($Device.GuestMachineName.Trim() -and $_."Device Hostname" -eq $Device.GuestMachineName -and ($_."Serial Number" -like $Device.GuestMachineSerialNumber -or $_.MacAddresses.macAddress -contains $Device.GuestHardwareNetworkAddress)) -or
$_."Device UID" -in $ForcedMatches.id
}
if (($Related_RMMDevices_Filtered | Measure-Object).Count -gt 0) {
$Related_RMMDevices = $Related_RMMDevices_Filtered
}
if (($Related_RMMDevices_Filtered | Measure-Object).Count -gt 1) {
# If there is still more than 1 match, try removing any matches based on a USB network adapters mac address (but still keep them if the hostname matches)
$Related_RMMDevices_Filtered = $Related_RMMDevices_Filtered | Where-Object { $_."Device Hostname" -eq $Device.Name -or $_."Device Hostname" -eq $Device.GuestMachineName -or $_.MacAddresses.macAddress -notlike $Device.GuestHardwareNetworkAddress -or ($_.MacAddresses.macAddress -like $Device.GuestHardwareNetworkAddress -and $_.MacAddresses.instance -notlike "*USB*" -and $_.MacAddresses.instance -notlike "*Ethernet Adapter*" -and $ConnectedMac.instance -like "*Plugable Ethernet*") }
if (($Related_RMMDevices_Filtered | Measure-Object).Count -gt 0) {
$Related_RMMDevices = $Related_RMMDevices_Filtered
}
}
}
# If we found related devices, add them to the matched device list
if (($Related_RMMDevices | Measure-Object).Count -gt 0) {
$MatchedDevice.rmm_matches = @($Related_RMMDevices."Device UID")
$MatchedDevice.rmm_hostname = @($Related_RMMDevices."Device Hostname")
}
}
}
# Add any missing RMM devices that no matches were found for
foreach ($Device in $RMM_Devices) {
if ($Device."Device UID" -in $MatchedDevices.rmm_matches) {
continue
}
$MatchedDevices += [PsCustomObject]@{
id = New-Guid
sc_matches = @()
sc_hostname = @()
rmm_matches = @($Device."Device UID")
rmm_hostname = @($Device."Device Hostname")
sophos_matches = @()
sophos_hostname = @()
itg_matches = @()
itg_hostname = @()
autotask_matches = @()
autotask_hostname = @()
jc_matches = @()
jc_hostname = @()
azure_matches = @()
azure_hostname = @()
azure_match_warning = @()
intune_matches = @()
intune_hostname = @()
ninite_matches = @()
ninite_hostname = @()
}
}
# Match Sophos devices
foreach ($Device in $Sophos_Devices) {
$CleanDeviceName = $Device.hostname -replace '\W', ''
$RelatedDevices = @()
$AddedForcedMatches = @()
$ForcedMatches = force_match -DeviceID $Device.id -Type "Sophos"
$ForcedMatches = $ForcedMatches | Where-Object { $_.type -like 'sc' -or $_.type -like 'rmm' }
$IgnoreSC = @(($ForcedMatches | Where-Object { $_.type -like 'sc' -and $_.match -eq $false }).id)
$IgnoreRMM = @(($ForcedMatches | Where-Object { $_.type -like 'rmm' -and $_.match -eq $false }).id)
$ForcedMatches = @($ForcedMatches | Where-Object { $_.id -ne $false -and $_.match -ne $false })
# Forced matches
if ($ForcedMatches) {
# Match IDs
foreach ($Match in $ForcedMatches) {
if ($Match.type -like 'rmm') {
$RMMMatches = @($MatchedDevices | Where-Object { $_.rmm_matches -contains $Match.id })
$RelatedDevices += $RMMMatches
$AddedForcedMatches += $RMMMatches.id
} elseif ($Match.type -like 'sc') {
$SCMatches = @($MatchedDevices | Where-Object { $_.sc_matches -contains $Match.id })
$RelatedDevices += $SCMatches
$AddedForcedMatches += $SCMatches.id
}
}
}
# If $IgnoreRMM and $IgnoreSC both contain $False, stop here as that means we dont want to match with any more devices. Create an empty entry first if we havent force matched any devices already.
if ($IgnoreRMM -contains $false -and $IgnoreSC -contains $false) {
if (!$DidForceMatches) {
$MatchedDevices += [PsCustomObject]@{
id = New-Guid
sc_matches = @()
sc_hostname = @()
rmm_matches = @()
rmm_hostname = @()
sophos_matches = @($Device.id)
sophos_hostname = @($Device.hostname)
itg_matches = @()
itg_hostname = @()
autotask_matches = @()
autotask_hostname = @()
jc_matches = @()
jc_hostname = @()
azure_matches = @()
azure_hostname = @()
azure_match_warning = @()
intune_matches = @()
intune_hostname = @()
ninite_matches = @()
ninite_hostname = @()