-
Notifications
You must be signed in to change notification settings - Fork 1
/
Invoke-IntuneCleanup.ps1
416 lines (342 loc) · 11.9 KB
/
Invoke-IntuneCleanup.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
<#
.DESCRIPTION
This script will remove duplicated devices based on the serial from Intune.
Remove duplicate intune devices based on device serial numbers
Caution with duplicates caused by some OEM's
Function adapted from https://www.wpninjas.ch/2019/09/cleanup-duplicated-devices-in-intune/
The Service Principal(RunAs) of the Azure Automation Workspace requires:
- MSGraph
- DeviceManagementManagedDevices.ReadWrite.All
.EXAMPLE
.NOTES
Author: Thomas Kurth/baseVISION
Date: 20.11.2021
History
001: First Version
ExitCodes:
99001: Could not Write to LogFile
99002: Could not Write to Windows Log
99003: Could not Set ExitMessageRegistry
#>
[CmdletBinding(SupportsShouldProcess=$True)]
Param()
## Manual Variable Definition
########################################################
$DebugPreference = "Continue"
$ScriptVersion = "001"
$ScriptName = "Invoke-IntuneCleanup"
$LogFilePathFolder = "C:\Windows\Logs"
$FallbackScriptPath = "C:\Windows" # This is only used if the filename could not be resolved(IE running in ISE)
# Log Configuration
$DefaultLogOutputMode = "Console" # "Console-LogFile","Console-WindowsEvent","LogFile-WindowsEvent","Console","LogFile","WindowsEvent","All"
$DefaultLogWindowsEventSource = $ScriptName
$DefaultLogWindowsEventLog = "CustomPS"
# Azure Automation
$RunningInAA = $false
$excludedSerialNumbers = @("Defaultstring", "ToBeFilledByO.E.M.","0")
#region Functions
########################################################
function Write-Log {
<#
.DESCRIPTION
Write text to a logfile with the current time.
.PARAMETER Message
Specifies the message to log.
.PARAMETER Type
Type of Message ("Info","Debug","Warn","Error").
.PARAMETER OutputMode
Specifies where the log should be written. Possible values are "Console","LogFile" and "Both".
.PARAMETER Exception
You can write an exception object to the log file if there was an exception.
.EXAMPLE
Write-Log -Message "Start process XY"
.NOTES
This function should be used to log information to console or log file.
#>
param(
[Parameter(Mandatory = $true, Position = 1)]
[String]
$Message
,
[Parameter(Mandatory = $false)]
[ValidateSet("Info", "Debug", "Warn", "Error")]
[String]
$Type = "Debug"
,
[Parameter(Mandatory = $false)]
[ValidateSet("Console-LogFile", "Console-WindowsEvent", "LogFile-WindowsEvent", "Console", "LogFile", "WindowsEvent", "All")]
[String]
$OutputMode = $DefaultLogOutputMode
,
[Parameter(Mandatory = $false)]
[Exception]
$Exception
)
$DateTimeString = Get-Date -Format "yyyy-MM-dd HH:mm:sszz"
$Output = ($DateTimeString + "`t" + $Type.ToUpper() + "`t" + $Message)
if ($Exception) {
$ExceptionString = ("[" + $Exception.GetType().FullName + "] " + $Exception.Message)
$Output = "$Output - $ExceptionString"
}
if ($OutputMode -eq "Console" -OR $OutputMode -eq "Console-LogFile" -OR $OutputMode -eq "Console-WindowsEvent" -OR $OutputMode -eq "All") {
if ($Type -eq "Error") {
Write-Error $output
}
elseif ($Type -eq "Warn") {
Write-Warning $output
}
elseif ($Type -eq "Debug") {
Write-Debug $output
}
else {
Write-Verbose $output -Verbose
}
}
if ($OutputMode -eq "LogFile" -OR $OutputMode -eq "Console-LogFile" -OR $OutputMode -eq "LogFile-WindowsEvent" -OR $OutputMode -eq "All") {
try {
Add-Content $LogFilePath -Value $Output -ErrorAction Stop
}
catch {
exit 99001
}
}
if ($OutputMode -eq "Console-WindowsEvent" -OR $OutputMode -eq "WindowsEvent" -OR $OutputMode -eq "LogFile-WindowsEvent" -OR $OutputMode -eq "All") {
try {
New-EventLog -LogName $DefaultLogWindowsEventLog -Source $DefaultLogWindowsEventSource -ErrorAction SilentlyContinue
switch ($Type) {
"Warn" {
$EventType = "Warning"
break
}
"Error" {
$EventType = "Error"
break
}
default {
$EventType = "Information"
}
}
Write-EventLog -LogName $DefaultLogWindowsEventLog -Source $DefaultLogWindowsEventSource -EntryType $EventType -EventId 1 -Message $Output -ErrorAction Stop
}
catch {
exit 99002
}
}
}
function New-Folder {
<#
.DESCRIPTION
Creates a Folder if it's not existing.
.PARAMETER Path
Specifies the path of the new folder.
.EXAMPLE
CreateFolder "c:\temp"
.NOTES
This function creates a folder if doesn't exist.
#>
param(
[Parameter(Mandatory = $True, Position = 1)]
[string]$Path
)
# Check if the folder Exists
if (Test-Path $Path) {
Write-Log "Folder: $Path Already Exists"
}
else {
New-Item -Path $Path -type directory | Out-Null
Write-Log "Creating $Path"
}
}
function Set-RegValue {
<#
.DESCRIPTION
Set registry value and create parent key if it is not existing.
.PARAMETER Path
Registry Path
.PARAMETER Name
Name of the Value
.PARAMETER Value
Value to set
.PARAMETER Type
Type = Binary, DWord, ExpandString, MultiString, String or QWord
#>
param(
[Parameter(Mandatory = $True)]
[string]$Path,
[Parameter(Mandatory = $True)]
[string]$Name,
[Parameter(Mandatory = $True)]
[AllowEmptyString()]
[string]$Value,
[Parameter(Mandatory = $True)]
[string]$Type
)
try {
$ErrorActionPreference = 'Stop' # convert all errors to terminating errors
Start-Transaction
if (Test-Path $Path -erroraction silentlycontinue) {
}
else {
New-Item -Path $Path -Force
Write-Log "Registry key $Path created"
}
$null = New-ItemProperty -Path $Path -Name $Name -PropertyType $Type -Value $Value -Force
Write-Log "Registry Value $Path, $Name, $Type, $Value set"
Complete-Transaction
}
catch {
Undo-Transaction
Write-Log "Registry value not set $Path, $Name, $Value, $Type" -Type Error -Exception $_.Exception
}
}
Function Invoke-Graph(){
<#
.SYNOPSIS
This function Requests information from Microsoft Graph
.DESCRIPTION
This function Requests information from Microsoft Graph and returns the value as Object[]
.EXAMPLE
Invoke-DocGraph -url ""
Returns "Type"
.NOTES
NAME: Thomas Kurth 3.3.2021
#>
[OutputType('System.Object[]')]
[cmdletbinding()]
param
(
[Parameter(Mandatory=$true,ParameterSetName = "FullPath")]
$FullUrl,
[Parameter(Mandatory=$true,ParameterSetName = "Path")]
[string]$Path,
[Parameter(Mandatory=$false,ParameterSetName = "Path")]
[string]$BaseUrl = "https://graph.microsoft.com/",
[Parameter(Mandatory=$false,ParameterSetName = "Path")]
[switch]$Beta,
[Parameter(Mandatory=$false,ParameterSetName = "Path")]
[string]$AcceptLanguage,
[Parameter(Mandatory=$false,ParameterSetName = "Path")]
[ValidateSet('GET','DELETE')]
[string]$Method = "GET"
)
if($PSCmdlet.ParameterSetName -eq "Path"){
if($Beta){
$version = "beta"
} else {
$version = "v1.0"
}
$FullUrl = "$BaseUrl$version$Path"
}
try{
$header = @{Authorization = "Bearer $($script:token.AccessToken)"}
if($AcceptLanguage){
$header.Add("Accept-Language",$AcceptLanguage)
}
$value = Invoke-RestMethod -Headers $header -Uri $FullUrl -Method $Method -ErrorAction Stop
} catch {
if($_.Exception.Response.StatusCode -eq "Forbidden"){
throw "Used application does not have sufficiant permission to access: $FullUrl"
} else {
Write-Error $_
}
}
return $value
}
#endregion
#region Dynamic Variables and Parameters
########################################################
# Try get actual ScriptName
try {
$CurrentFileNameTemp = $MyInvocation.MyCommand.Name
If ($CurrentFileNameTemp -eq $null -or $CurrentFileNameTemp -eq "") {
$CurrentFileName = "NotExecutedAsScript"
}
else {
$CurrentFileName = $CurrentFileNameTemp
}
}
catch {
$CurrentFileName = $LogFilePathScriptName
}
$LogFilePath = "$LogFilePathFolder\{0}_{1}_{2}.log" -f ($ScriptName -replace ".ps1", ''), $ScriptVersion, (Get-Date -uformat %Y%m%d%H%M)
# Try get actual ScriptPath
try {
try {
$ScriptPathTemp = Split-Path $MyInvocation.MyCommand.Path
}
catch {
}
if ([String]::IsNullOrWhiteSpace($ScriptPathTemp)) {
$ScriptPathTemp = Split-Path $MyInvocation.InvocationName
}
If ([String]::IsNullOrWhiteSpace($ScriptPathTemp)) {
$ScriptPath = $FallbackScriptPath
}
else {
$ScriptPath = $ScriptPathTemp
}
}
catch {
$ScriptPath = $FallbackScriptPath
}
#endregion
#region Initialization
########################################################
if (!(Test-Path $LogFilePathFolder)) {
New-Folder $LogFilePathFolder
}
Write-Log "Start Script $Scriptname"
if($RunningInAA){
$connection = Get-AutomationConnection -Name AzureRunAsConnection
# Azure AD
$AADAuthBody = @{
TenantID = $Connection.TenantId
ClientID = $Connection.ApplicationID
ClientCertificate = (get-item Cert:\CurrentUser\my\$($Connection.CertificateThumbprint))
}
} else {
# Azure AD - intune default app registration will force interactive
$AADAuthBody = @{
ClientId = "d1ddf0e4-d672-4dae-b554-9d5bdfd93547"
RedirectUri = "urn:ietf:wg:oauth:2.0:oob"
}
}
try {
Write-log -Type Info -message "Connecting to MS Graph ..."
if($null -eq $GraphAuthHeader){
#get Azure Token
$accesstokenazure = Get-MsalToken @AADAuthBody
#Azure Header
$script:token = $accesstokenazure
}
Write-Log -Message "Token successfully created" -Type Info
}
catch {
Write-Log -Message "Get Token Failed" -Type Error -Exception $_.Exception
throw "Get Token failed, stopping script."
}
#endregion
#region Main Script
########################################################
$devices = (Invoke-Graph -Path "/deviceManagement/managedDevices").Value
Write-Log -Message "Found $($devices.Count) devices."
$deviceGroups = $devices | Where-Object { -not [String]::IsNullOrWhiteSpace($_.serialNumber) -and $_.serialNumber -notin $excludedSerialNumbers } | Group-Object -Property serialNumber
$duplicatedDevices = $deviceGroups | Where-Object { $_.Count -gt 1 }
Write-Log -Message "Found $($duplicatedDevices.Count) serialNumbers with duplicated entries"
foreach ($duplicatedDevice in $duplicatedDevices) {
# Find device which is the newest.
$newestDevice = $duplicatedDevice.Group | Sort-Object -Property lastSyncDateTime -Descending | Select-Object -First 1
Write-Log -Message "Serial $($duplicatedDevice.Name)"
Write-Log -Message "# Keep $($newestDevice.deviceName) $($newestDevice.lastSyncDateTime)"
foreach ($oldDevice in ($duplicatedDevice.Group | Sort-Object -Property lastSyncDateTime -Descending | Select-Object -Skip 1)) {
Write-Log -Message "# Remove $($oldDevice.deviceName) $($oldDevice.lastSyncDateTime)"
if ($PSCmdlet.ShouldProcess($oldDevice.id, "Deleting device")) {
Invoke-Graph -Path "/deviceManagement/managedDevices/$($oldDevice.id)" -Method "DELETE"
}
}
}
#endregion
#region Finishing
########################################################
Write-log -message "End Script $scriptname" -Type Info
#endregion