forked from stevecapacity/intune-device-migration-8
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreboot.ps1
More file actions
562 lines (522 loc) · 19.7 KB
/
reboot.ps1
File metadata and controls
562 lines (522 loc) · 19.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
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
<# REBOOT.PS1
Synopsis
Reboot.ps1 automatically changes the userSid and user profile ownership to the new user and reboots the machine.
DESCRIPTION
This script is used to change ownership of the original user profile to the destination user and then reboot the machine. It is executed by the 'reboot' scheduled task.
USE
.\reboot.ps1
.OWNER
Steve Weiner
.CONTRIBUTORS
Logan Lautt
#>
$ErrorActionPreference = "SilentlyContinue"
# log function
function log()
{
[Cmdletbinding()]
Param(
[Parameter(Mandatory=$true)]
[string]$message
)
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss tt"
Write-Output "$timestamp - $message"
}
# Import config settings from JSON file
$config = Get-Content "C:\ProgramData\IntuneMigration\config.json" | ConvertFrom-Json
# Start Transcript
Start-Transcript -Path "$($config.logPath)\reboot.log" -Verbose
log "Starting Reboot.ps1..."
# Initialize script
$localPath = $config.localPath
if(!(Test-Path $localPath))
{
log "$($localPath) does not exist. Creating..."
mkdir $localPath
}
else
{
log "$($localPath) already exists."
}
# Check context
$context = whoami
log "Running as $($context)"
# disable reboot task
log "Disabling reboot task..."
Disable-ScheduledTask -TaskName "Reboot"
log "Reboot task disabled"
# disable auto logon
Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" -Name "AutoAdminLogon" -Value 0 -Verbose
log "Auto logon enabled."
# set new wallpaper
$wallpaper = (Get-ChildItem -Path $config.localPath -Filter "*.jpg" -Recurse).FullName
if($wallpaper)
{
log "Setting wallpaper..."
Copy-Item -Path $wallpaper -Destination "C:\Windows\Web\Wallpaper" -Force
$imgPath = "C:\Windows\Web\Wallpaper\$($wallpaper | Split-Path -Leaf)"
[string]$desktopScreenPath = "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\PersonalizationCSP"
log "Setting Lock screen wallpaper..."
reg.exe add $desktopScreenPath /v "DesktopImagePath" /t REG_SZ /d $imgPath /f | Out-Host
reg.exe add $desktopScreenPath /v "DesktopImageStatus" /t REG_DWORD /d 1 /f | Out-Host
}
# Retrieve variables from registry
log "Retrieving variables from registry..."
$regKey = "Registry::$($config.regPath)"
$values = Get-ItemProperty -Path $regKey
$values.PSObject.Properties | ForEach-Object {
$name = $_.Name
$value = $_.Value
if(![string]::IsNullOrEmpty($value))
{
log "Retrieved $($name): $value"
New-Variable -Name $name -Value $value -Force
}
else
{
log "Error retrieving $name"
ex
}
}
if($OLD_SID -eq $NEW_SID)
{
log "Old SID $($OLD_SID) and new SID $($NEW_SID) are the same. Skipping new profile creation."
}
else
{
# Remove aadBrokerPlugin from profile
$aadBrokerPath = (Get-ChildItem -Path "$($OLD_profilePath)\AppData\Local\Packages" -Recurse | Where-Object {$_.Name -match "Microsoft.AAD.BrokerPlugin_*"}).FullName
if($aadBrokerPath)
{
log "Removing aadBrokerPlugin from profile..."
Remove-Item -Path $aadBrokerPath -Recurse -Force
log "aadBrokerPlugin removed"
}
else
{
log "aadBrokerPlugin not found"
}
# Create new user profile
log "Creating $($NEW_SAMName) profile..."
Add-Type -TypeDefinition @"
using System;
using System.Security.Principal;
using System.Runtime.InteropServices;
namespace UserProfile {
public static class Class {
[DllImport("userenv.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern int CreateProfile(
[MarshalAs(UnmanagedType.LPWStr)] String pszUserSid,
[MarshalAs(UnmanagedType.LPWStr)] String pszUserName,
[Out][MarshalAs(UnmanagedType.LPWStr)] System.Text.StringBuilder pszProfilePath,
uint cchProfilePath
);
}
}
"@
$sb = New-Object System.Text.StringBuilder(260)
$pathLen = $sb.Capacity
try {
$CreateProfileReturn = [UserProfile.Class]::CreateProfile($NEW_SID, $NEW_SAMName, $sb, $pathLen)
} catch {
Write-Error $_.Exception.Message
}
switch ($CreateProfileReturn) {
0 {
Write-Output "User profile created successfully at path: $($sb.ToString())"
}
-2147024713 {
Write-Output "User profile already exists."
}
default {
throw "An error occurred when creating the user profile: $CreateProfileReturn"
}
}
# Delete New profile
log "Deleting new profile..."
$newProfile = Get-CimInstance -ClassName Win32_UserProfile | Where-Object {$_.SID -eq $NEW_SID}
try
{
Remove-CimInstance -InputObject $newProfile -Verbose | Out-Null
log "New profile deleted."
}
catch
{
$message = $_.Exception.Message
log "Failed to delete new profile: $message"
log "Exiting script..."
shutdown -r -t 05
exit 1
}
# Change ownership of user profile
log "Changing ownership of user profile..."
$currentProfile = Get-CimInstance -ClassName Win32_UserProfile | Where-Object {$_.SID -eq $OLD_SID}
$changes = @{
NewOwnerSID = $NEW_SID
Flags = 0
}
try
{
$currentProfile | Invoke-CimMethod -MethodName ChangeOwner -Arguments $changes | Out-Null
log "User profile ownership changed."
}
catch
{
$message = $_.Exception.Message
log "Failed to change user profile ownership: $message"
log "Exiting script..."
shutdown -r -t 05
exit 1
}
# Cleanup logon cache
function cleanupLogonCache()
{
Param(
[string]$logonCache = "HKLM:\SOFTWARE\Microsoft\IdentityStore\LogonCache",
[string]$oldUPN = $OLD_UPN
)
log "Cleaning up logon cache..."
$logonCacheGUID = (Get-ChildItem -Path $logonCache | Select-Object Name | Split-Path -Leaf).trim('{}')
foreach($GUID in $logonCacheGUID)
{
$subKeys = Get-ChildItem -Path "$logonCache\$GUID" -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Name | Split-Path -Leaf
if(!($subKeys))
{
log "No subkeys found for $GUID"
continue
}
else
{
$subKeys = $subKeys.trim('{}')
foreach($subKey in $subKeys)
{
if($subKey -eq "Name2Sid" -or $subKey -eq "SAM_Name" -or $subKey -eq "Sid2Name")
{
$subFolders = Get-ChildItem -Path "$logonCache\$GUID\$subKey" -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Name | Split-Path -Leaf
if(!($subFolders))
{
log "Error - no sub folders found for $subKey"
continue
}
else
{
$subFolders = $subFolders.trim('{}')
foreach($subFolder in $subFolders)
{
$cacheUsername = Get-ItemPropertyValue -Path "$logonCache\$GUID\$subKey\$subFolder" -Name "IdentityName" -ErrorAction SilentlyContinue
if($cacheUsername -eq $oldUserName)
{
Remove-Item -Path "$logonCache\$GUID\$subKey\$subFolder" -Recurse -Force
log "Registry key deleted: $logonCache\$GUID\$subKey\$subFolder"
continue
}
}
}
}
}
}
}
}
# run cleanupLogonCache
log "Running cleanupLogonCache..."
try
{
cleanupLogonCache
log "cleanupLogonCache completed"
}
catch
{
$message = $_.Exception.Message
log "Failed to run cleanupLogonCache: $message"
log "Exiting script..."
exit 1
}
# cleanup identity store cache
function cleanupIdentityStore()
{
Param(
[string]$idCache = "HKLM:\SOFTWARE\Microsoft\IdentityStore\Cache",
[string]$oldUserName = $OLD_UPN
)
log "Cleaning up identity store cache..."
$idCacheKeys = (Get-ChildItem -Path $idCache | Select-Object Name | Split-Path -Leaf).trim('{}')
foreach($key in $idCacheKeys)
{
$subKeys = Get-ChildItem -Path "$idCache\$key" -ErrorAction SilentlyContinue | Select-Object Name | Split-Path -Leaf
if(!($subKeys))
{
log "No keys listed under '$idCache\$key' - skipping..."
continue
}
else
{
$subKeys = $subKeys.trim('{}')
foreach($subKey in $subKeys)
{
$subFolders = Get-ChildItem -Path "$idCache\$key\$subKey" -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Name | Split-Path -Leaf
if(!($subFolders))
{
log "No subfolders detected for $subkey- skipping..."
continue
}
else
{
$subFolders = $subFolders.trim('{}')
foreach($subFolder in $subFolders)
{
$idCacheUsername = Get-ItemPropertyValue -Path "$idCache\$key\$subKey\$subFolder" -Name "UserName" -ErrorAction SilentlyContinue
if($idCacheUsername -eq $oldUserName)
{
Remove-Item -Path "$idCache\$key\$subKey\$subFolder" -Recurse -Force
log "Registry path deleted: $idCache\$key\$subKey\$subFolder"
continue
}
}
}
}
}
}
}
# run cleanup identity store cache if not domain joined
if($OLD_domainJoined -eq "NO")
{
log "Running cleanupIdentityStore..."
try
{
cleanupIdentityStore
log "cleanupIdentityStore completed"
}
catch
{
$message = $_.Exception.Message
log "Failed to run cleanupIdentityStore: $message"
log "Exiting script..."
ex
}
}
else
{
log "Machine is domain joined - skipping cleanupIdentityStore."
}
# update samname in identityStore LogonCache (this is required when displaynames are the same in both tenants, and new samname gets random characters added at the end)
function updateSamNameLogonCache()
{
Param(
[string]$logonCache = "HKLM:\SOFTWARE\Microsoft\IdentityStore\LogonCache",
[string]$targetSAMName = $OLD_SAMName
)
if($NEW_SAMName -like "$($OLD_SAMName)_*" -or $NEW_SAMName -like "$($OLD_SAMName).*")
{
log "New user is $NEW_SAMName, which is the same as $OLD_SAMName with _##### appended to the end. Removing appended characters on SamName in LogonCache registry..."
$logonCacheGUID = (Get-ChildItem -Path $logonCache | Select-Object Name | Split-Path -Leaf).trim('{}')
foreach($GUID in $logonCacheGUID)
{
$subKeys = Get-ChildItem -Path "$logonCache\$GUID" -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Name | Split-Path -Leaf
if(!($subKeys))
{
log "No subkeys found for $GUID"
continue
}
else
{
$subKeys = $subKeys.trim('{}')
foreach($subKey in $subKeys)
{
if($subKey -eq "Name2Sid")
{
$subFolders = Get-ChildItem -Path "$logonCache\$GUID\$subKey" -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Name | Split-Path -Leaf
if(!($subFolders))
{
log "Error - no sub folders found for $subKey"
continue
}
else
{
$subFolders = $subFolders.trim('{}')
foreach($subFolder in $subFolders)
{
$detectedUserSID = Get-ItemProperty -Path "$logonCache\$GUID\$subKey\$subFolder" | Select-Object -ExpandProperty "Sid" -ErrorAction SilentlyContinue
if($detectedUserSID -eq $NEW_SID)
{
Set-ItemProperty -Path "$logonCache\$GUID\$subKey\$subFolder" -Name "SAMName" -Value $targetSAMName -Force
log "Attempted to update SAMName value (in Name2Sid registry folder) to '$targetSAMName'."
continue
}
else
{
log "Detected Sid '$detectedUserSID' is for different user - skipping Sid in Name2Sid registry folder..."
}
}
}
}
elseif($subKey -eq "SAM_Name")
{
$subFolders = Get-ChildItem -Path "$logonCache\$GUID\$subKey" -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Name | Split-Path -Leaf
if(!($subFolders))
{
log "Error - no sub folders found for $subKey"
continue
}
else
{
$subFolders = $subFolders.trim('{}')
foreach($subFolder in $subFolders)
{
$detectedUserSID = Get-ItemProperty -Path "$logonCache\$GUID\$subKey\$subFolder" | Select-Object -ExpandProperty "Sid" -ErrorAction SilentlyContinue
if($detectedUserSID -eq $NEW_SID)
{
Rename-Item "$logonCache\$GUID\$subKey\$subFolder" -NewName $targetSAMName -Force
log "Attempted to update SAM_Name key name (in SAM_Name registry folder) to '$targetSAMName'."
continue
}
else
{
log "Skipping different user in SAM_Name registry folder (User: $subFolder, SID: $detectedUserSID)..."
}
}
}
}
elseif($subKey -eq "Sid2Name")
{
$subFolders = Get-ChildItem -Path "$logonCache\$GUID\$subKey" -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Name | Split-Path -Leaf
if(!($subFolders))
{
log "Error - no sub folders found for $subKey"
continue
}
else
{
$subFolders = $subFolders.trim('{}')
foreach($subFolder in $subFolders)
{
if($subFolder -eq $NEW_SID)
{
Set-ItemProperty -Path "$logonCache\$GUID\$subKey\$subFolder" -Name "SAMName" -Value $targetSAMName -Force
log "Attempted to update SAM_Name value (in Sid2Name registry folder) to '$targetSAMName'."
continue
}
else
{
log "Skipping different user SID ($subFolder) in Sid2Name registry folder..."
}
}
}
}
}
}
}
}
else
{
log "New username is $NEW_SAMName, which does not match older username ($OLD_SAMName) with _##### appended to end. SamName LogonCache registry will not be updated."
}
}
# run updateSamNameLogonCache
log "Running updateSamNameLogonCache..."
try
{
updateSamNameLogonCache
log "updateSamNameLogonCache completed"
}
catch
{
$message = $_.Exception.Message
log "Failed to run updateSamNameLogonCache: $message"
log "Exiting script..."
exit 1
}
# update samname in identityStore Cache (this is required when displaynames are the same in both tenants, and new samname gets random characters added at the end)
function updateSamNameIdentityStore()
{
Param(
[string]$idCache = "HKLM:\Software\Microsoft\IdentityStore\Cache",
[string]$targetSAMName = $OLD_SAMName
)
if($NEW_SAMName -like "$($OLD_SAMName)_*")
{
log "Cleaning up identity store cache..."
$idCacheKeys = (Get-ChildItem -Path $idCache | Select-Object Name | Split-Path -Leaf).trim('{}')
foreach($key in $idCacheKeys)
{
$subKeys = Get-ChildItem -Path "$idCache\$key" -ErrorAction SilentlyContinue | Select-Object Name | Split-Path -Leaf
if(!($subKeys))
{
log "No keys listed under '$idCache\$key' - skipping..."
continue
}
else
{
$subKeys = $subKeys.trim('{}')
foreach($subKey in $subKeys)
{
$subFolders = Get-ChildItem -Path "$idCache\$key\$subKey" -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Name | Split-Path -Leaf
if(!($subFolders))
{
log "No subfolders detected for $subkey- skipping..."
continue
}
else
{
$subFolders = $subFolders.trim('{}')
foreach($subFolder in $subFolders)
{
if($subFolder -eq $NEW_SID)
{
Set-ItemProperty -Path "$idCache\$key\$subKey\$subFolder" -Name "SAMName" -Value $targetSAMName -Force
log "Attempted to update SAMName value to $targetSAMName."
}
else
{
log "Skipping different user SID ($subFolder) in $subKey registry folder..."
}
}
}
}
}
}
}
else
{
log "New username is $NEW_SAMName, which does not match older username ($OLD_SAMName) with _##### appended to end. SamName IdentityStore registry will not be updated."
}
}
# run updateSamNameIdentityStore if not domain joined
if($OLD_domainJoined -eq "NO")
{
log "Running updateSamNameIdentityStore..."
try
{
updateSamNameIdentityStore
log "updateSamNameIdentityStore completed"
}
catch
{
$message = $_.Exception.Message
log "Failed to run updateSamNameIdentityStore: $message"
log "Exiting script..."
ex
}
}
else
{
log "Machine is domain joined - skipping updateSamNameIdentityStore."
}
}
# enable logon provider
reg.exe add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Authentication\Credential Providers\{60b78e88-ead8-445c-9cfd-0b87f74ea6cd}" /v "Disabled" /t REG_DWORD /d 0 /f | Out-Host
log "Enabled logon provider."
# set lock screen caption
if($config.targetTenant.tenantName)
{
$tenant = $config.targetTenant.tenantName
}
else
{
$tenant = $config.sourceTenant.tenantName
}
reg.exe add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System" /v "legalnoticecaption" /t REG_SZ /d "Welcome to $($tenant)" /f | Out-Host
reg.exe add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System" /v "legalnoticetext" /t REG_SZ /d "Please log in with your new email address" /f | Out-Host
log "Lock screen caption set."
log "Reboot.ps1 complete"
Stop-Transcript
shutdown -r -t 00