/
Runbook.ps1
359 lines (290 loc) · 13.2 KB
/
Runbook.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
param
(
[Parameter (Mandatory=$false)]
[object] $WebhookData
)
# Connect to Intune
$resourceURL = "https://graph.microsoft.com/"
$response = [System.Text.Encoding]::Default.GetString((Invoke-WebRequest -UseBasicParsing -Uri "$($env:IDENTITY_ENDPOINT)?resource=$resourceURL" -Method 'GET' -Headers @{'X-IDENTITY-HEADER' = "$env:IDENTITY_HEADER"; 'Metadata' = 'True'}).RawContentStream.ToArray()) | ConvertFrom-Json
#$script:authToken = $response.access_token
$script:authToken = @{
'Content-Type' = 'application/json'
'Authorization' = "Bearer " + $response.access_token
}
####################################################Functions for Import####################################################
Function Get-AutoPilotDevice(){
[cmdletbinding()]
param
(
[Parameter(Mandatory=$false)] $id
)
# Defining Variables
if ($id) {
$uri = "https://graph.microsoft.com/v1.0/deviceManagement/windowsAutopilotDeviceIdentities/$id"
}
else {
$uri = "https://graph.microsoft.com/v1.0/deviceManagement/windowsAutopilotDeviceIdentities/$Resource"
}
try {
$response = Invoke-RestMethod -Uri $uri -Headers $authToken -Method Get
if ($id) {
$response
}
else {
$response.Value
}
}
catch {
$ex = $_.Exception
$errorResponse = $ex.Response.GetResponseStream()
$reader = New-Object System.IO.StreamReader($errorResponse)
$reader.BaseStream.Position = 0
$reader.DiscardBufferedData()
$responseBody = $reader.ReadToEnd();
Write-Output "Response content:`n$responseBody"
Write-Error "Request to $Uri failed with HTTP Status $($ex.Response.StatusCode) $($ex.Response.StatusDescription)"
break
}
}
Function Get-AutoPilotImportedDevice(){
[cmdletbinding()]
param
(
[Parameter(Mandatory=$false)] $id
)
if ($id) {
$uri = "https://graph.microsoft.com/v1.0/deviceManagement/importedWindowsAutopilotDeviceIdentities/$id"
}
else {
$uri = "https://graph.microsoft.com/v1.0/deviceManagement/importedWindowsAutopilotDeviceIdentities/$Resource"
}
$response = Invoke-RestMethod -Uri $uri -Headers $authToken -Method Get
if ($id) {
$response
}
else {
$response.Value
}
}
Function Add-AutoPilotImportedDevice(){
[cmdletbinding()]
param
(
[Parameter(Mandatory=$true)] $serialNumber,
[Parameter(Mandatory=$true)] $hardwareIdentifier,
[Parameter(Mandatory=$false)] $orderIdentifier
)
# Defining Variables
$uri = "https://graph.microsoft.com/v1.0/deviceManagement/importedWindowsAutopilotDeviceIdentities/$Resource"
$json = @"
{
"@odata.type": "#microsoft.graph.importedWindowsAutopilotDeviceIdentity",
"groupTag": "$orderIdentifier",
"serialNumber": "$serialNumber",
"productKey": "",
"hardwareIdentifier": "$hardwareIdentifier",
"state": {
"@odata.type": "microsoft.graph.importedWindowsAutopilotDeviceIdentityState",
"deviceImportStatus": "pending",
"deviceRegistrationId": "",
"deviceErrorCode": 0,
"deviceErrorName": ""
}
}
"@
try {
$Response=(Invoke-RestMethod -Uri $uri -Headers $authToken -Method Post -Body $json -ContentType "application/json").ID
return $Response
}
catch {
$ex = $_.Exception
$errorResponse = $ex.Response.GetResponseStream()
$reader = New-Object System.IO.StreamReader($errorResponse)
$reader.BaseStream.Position = 0
$reader.DiscardBufferedData()
$responseBody = $reader.ReadToEnd();
Write-Output "Response content:`n$responseBody"
Write-Error "Request to $Uri failed with HTTP Status $($ex.Response.StatusCode) $($ex.Response.StatusDescription)"
break
}
}
Function Remove-AutoPilotImportedDevice(){
[cmdletbinding()]
param
(
[Parameter(Mandatory=$true)] $id
)
$uri = "https://graph.microsoft.com/v1.0/deviceManagement/importedWindowsAutopilotDeviceIdentities/$id"
try {
Invoke-RestMethod -Uri $uri -Headers $authToken -Method Delete | Out-Null
}
catch {
$ex = $_.Exception
$errorResponse = $ex.Response.GetResponseStream()
$reader = New-Object System.IO.StreamReader($errorResponse)
$reader.BaseStream.Position = 0
$reader.DiscardBufferedData()
$responseBody = $reader.ReadToEnd();
Write-Output "Response content:`n$responseBody"
Write-Error "Request to $Uri failed with HTTP Status $($ex.Response.StatusCode) $($ex.Response.StatusDescription)"
break
}
}
####################################################Import Main Function####################################################
Function Import-AutoPilotCSV(){
[cmdletbinding()]
param
(
[Parameter(Mandatory=$true)] $Serial,
[Parameter(Mandatory=$true)] $GroupTag,
[Parameter(Mandatory=$true)] $hash
)
$ImportID=Add-AutoPilotImportedDevice -serialNumber $serial -hardwareIdentifier $hash -orderIdentifier $GroupTag
# While we could keep a list of all the IDs that we added and then check each one, it is
# easier to just loop through all of them
$processingCount = 1
while ($processingCount -gt 0)
{
Start-Sleep 60
$deviceStatuses = Get-AutoPilotImportedDevice -id $ImportID
$deviceCount = "1"
# Check to see if any devices are still processing (enhanced by check for pending)
$processingCount = 0
foreach ($device in $deviceStatuses){
if ($($device.state.deviceImportStatus).ToLower() -eq "unknown" -or $($device.state.deviceImportStatus).ToLower() -eq "pending") {
$processingCount = $processingCount + 1
}
}
Write-Output "Waiting for $processingCount of $deviceCount"
# Still processing? Sleep before trying again.
if ($processingCount -gt 0){
Start-Sleep 15
}
}
# Generate some statistics for reporting...
$global:successCount = 0
$global:errorCount = 0
$global:softErrorCount = 0
$global:errorList = @{}
$global:successList = @{}
ForEach ($deviceStatus in $deviceStatuses) {
if ($($deviceStatus.state.deviceImportStatus).ToLower() -eq 'success' -or $($deviceStatus.state.deviceImportStatus).ToLower() -eq 'complete') {
$global:successCount += 1
$global:successList.Add($deviceStatus.serialNumber, $deviceStatus.state)
} elseif ($($deviceStatus.state.deviceImportStatus).ToLower() -eq 'error') {
$global:errorCount += 1
# ZtdDeviceAlreadyAssigned will be counted as soft error, free to delete
if ($($deviceStatus.state.deviceErrorCode) -eq 806) {
$global:softErrorCount += 1
}
$global:errorList.Add($deviceStatus.serialNumber, $deviceStatus.state)
}
}
# Display the statuses
$deviceStatuses | ForEach-Object {
Write-Output "Serial number $($_.serialNumber): $($_.state.deviceImportStatus), $($_.state.deviceErrorCode), $($_.state.deviceErrorName)"
$ImportedAutopilotDevice = New-Object System.Object
$ImportedAutopilotDevice | Add-Member -MemberType NoteProperty -Name "SerialNumber" -Value $($_.serialNumber) -Force
$ImportedAutopilotDevice | Add-Member -MemberType NoteProperty -Name "Status" -Value $($_.state.deviceImportStatus) -Force
$ImportedAutopilotDevice | Add-Member -MemberType NoteProperty -Name "ErrorCode" -Value $($_.state.deviceErrorCode) -Force
$ImportedAutopilotDevice | Add-Member -MemberType NoteProperty -Name "ErrorName" -Value $($_.state.deviceErrorName) -Force
$AutopilotJson = $ImportedAutopilotDevice | ConvertTo-Json
$ResponseLAUpload = Send-LogAnalyticsData -customerId $WorkspaceID -sharedKey $SharedKey -body ([System.Text.Encoding]::UTF8.GetBytes($AutopilotJson)) -logType $AutopilotLog -ErrorAction Stop
Write-Output $ResponseLAUpload
}
# Cleanup the imported device records
$deviceStatuses | ForEach-Object {
Remove-AutoPilotImportedDevice -id $_.id
}
}
Function Invoke-AutopilotSync(){
$uri = "https://graph.microsoft.com/v1.0/deviceManagement/windowsAutopilotSettings/sync"
try {
$response = Invoke-RestMethod -Uri $uri -Headers $authToken -Method Post
$response.Value
}
catch {
$ex = $_.Exception
$errorResponse = $ex.Response.GetResponseStream()
$reader = New-Object System.IO.StreamReader($errorResponse)
$reader.BaseStream.Position = 0
$reader.DiscardBufferedData()
$responseBody = $reader.ReadToEnd();
Write-Host "Response content:`n$responseBody" -f Red
Write-Error "Request to $Uri failed with HTTP Status $($ex.Response.StatusCode) $($ex.Response.StatusDescription)"
# break
}
}
####################################################Functions for Log Analytics###################################################
Function New-Signature ($customerId, $sharedKey, $date, $contentLength, $method, $contentType, $resource) {
$xHeaders = "x-ms-date:" + $date
$stringToHash = $method + "`n" + $contentLength + "`n" + $contentType + "`n" + $xHeaders + "`n" + $resource
$bytesToHash = [Text.Encoding]::UTF8.GetBytes($stringToHash)
$keyBytes = [Convert]::FromBase64String($sharedKey)
$sha256 = New-Object System.Security.Cryptography.HMACSHA256
$sha256.Key = $keyBytes
$calculatedHash = $sha256.ComputeHash($bytesToHash)
$encodedHash = [Convert]::ToBase64String($calculatedHash)
$authorization = 'SharedKey {0}:{1}' -f $customerId, $encodedHash
return $authorization
}#endfunction
Function Send-LogAnalyticsData($customerId, $sharedKey, $body, $logType) {
$method = "POST"
$contentType = "application/json"
$resource = "/api/logs"
$rfc1123date = [DateTime]::UtcNow.ToString("r")
$contentLength = $body.Length
$signature = New-Signature `
-customerId $customerId `
-sharedKey $sharedKey `
-date $rfc1123date `
-contentLength $contentLength `
-method $method `
-contentType $contentType `
-resource $resource
$uri = "https://" + $customerId + ".ods.opinsights.azure.com" + $resource + "?api-version=2016-04-01"
#validate that payload data does not exceed limits
if ($body.Length -gt (31.9 *1024*1024))
{
throw("Upload payload is too big and exceed the 32Mb limit for a single upload. Please reduce the payload size. Current payload size is: " + ($body.Length/1024/1024).ToString("#.#") + "Mb")
}
$payloadsize = ("Upload payload size is " + ($body.Length/1024).ToString("#.#") + "Kb ")
$headers = @{
"Authorization" = $signature;
"Log-Type" = $logType;
"x-ms-date" = $rfc1123date;
"time-generated-field" = $TimeStampField;
}
$response = Invoke-WebRequest -Uri $uri -Method $method -ContentType $contentType -Headers $headers -Body $body -UseBasicParsing
$statusmessage = "$($response.StatusCode) : $($payloadsize)"
return $statusmessage
}#endfunction
####################################################Connect to Ressources###################################################
$global:totalCount = 0
$AutopilotZTDID=""
$AutopilotMDM=""
if ($WebhookData)
{
#Define WorkspaceID
$WorkspaceID = Get-AutomationVariable -Name 'WorkspaceID'
$SharedKey = Get-AutomationVariable -Name 'WSSharedKey'
#Define Log Analytics Workspace Subscription ID
$SubscriptionID = Get-AutomationVariable -Name 'LASubscriptionID'
#Define Autopilot Import Log Name
$AutopilotLog = "Autopilot_Import"
# DO NOT DELETE TimeStampField - IT WILL BREAK LA Injection
$TimeStampField = ""
Connect-AzAccount -Identity -Subscription $SubscriptionID
$WebhookData=(ConvertFrom-Json -InputObject $WebhookData)
#write-output $WebhookData.RequestBody
$Client=(ConvertFrom-Json -InputObject $WebhookData.RequestBody)
$serial=$client.SN
$GroupTag=$Client.GroupTag
$hash=$Client.Hash
####################################################Main logic Import###################################################
# Main logic Import
Import-AutoPilotCSV -Serial $Serial -GroupTag $GroupTag -Hash $hash
# Sync new devices to Intune
Write-output "Triggering Sync to Intune."
Invoke-AutopilotSync
}