-
Notifications
You must be signed in to change notification settings - Fork 69
/
Invoke-USMTGUI.ps1
executable file
·2525 lines (2241 loc) · 117 KB
/
Invoke-USMTGUI.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
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
Migrate user state from one PC to another using USMT.
.DESCRIPTION
Migrate user state from one PC to another using USMT. Intended for domain joined computers.
By default, all user profile data except Favorites and Documents will be included.
Tool also allows for user to specify additional folders to include.
.NOTES
USMT environmental variables: https://technet.microsoft.com/en-us/library/cc749104(v=ws.10).aspx
#>
begin {
# Define the script version
$ScriptVersion = "3.5.4"
# Set ScripRoot variable to the path which the script is executed from
$ScriptRoot = if ($PSVersionTable.PSVersion.Major -lt 3) {
Split-Path -Path $MyInvocation.MyCommand.Path
}
else {
$PSScriptRoot
}
# Load the options in the Config file
. "$ScriptRoot\USMT\Config.ps1"
# Set a value for the wscript comobject
$WScriptShell = New-Object -ComObject wscript.shell
function Update-Log {
param(
[string] $Message,
[string] $Color = 'White',
[switch] $NoNewLine
)
$LogTextBox.SelectionColor = $Color
$LogTextBox.AppendText("$Message")
if (-not $NoNewLine) { $LogTextBox.AppendText("`n") }
$LogTextBox.Update()
$LogTextBox.ScrollToCaret()
}
function Get-IPAddress { (Test-Connection -ComputerName (hostname) -Count 1).IPV4Address.IPAddressToString }
function Get-UserProfileLastLogin {
param(
[string]$Domain,
[string]$UserName
)
$CurrentUser = try { ([ADSI]"WinNT://$Domain/$UserName") } catch { }
if ($CurrentUser.Properties.LastLogin) {
try {
[datetime](-join $CurrentUser.Properties.LastLogin)
}
catch {
-join $CurrentUser.Properties.LastLogin
}
}
elseif ($CurrentUser.Properties.Name) {
}
else {
'N/A'
}
}
function Get-UserProfiles {
# Get all user profiles on this PC and let the user select which ones to migrate
$RegKey = 'Registry::HKey_Local_Machine\Software\Microsoft\Windows NT\CurrentVersion\ProfileList\*'
# Return each profile on this computer
Get-ItemProperty -Path $RegKey | ForEach-Object {
try {
$SID = New-object System.Security.Principal.SecurityIdentifier($_.PSChildName)
try {
$User = $SID.Translate([System.Security.Principal.NTAccount]).Value
# Don't show NT Authority accounts
if ($User -notlike 'NT Authority\*') {
$Domain = $User.Split('\')[0]
$UserName = $User.Split('\')[1]
if ($Script:QueryLastLogon) {
$LastLogin = Get-UserProfileLastLogin -Domain $Domain -UserName $UserName
}
else {
$LastLogin = 'N/A'
}
$ProfilePath = Get-UserProfilePath -Domain $Domain -UserName $UserName
# Create and return a custom object for each user found
$UserObject = New-Object psobject
$UserObject | Add-Member -MemberType NoteProperty -Name Domain -Value $Domain
$UserObject | Add-Member -MemberType NoteProperty -Name UserName -Value $UserName
$UserObject | Add-Member -MemberType NoteProperty -Name LastLogin -Value $LastLogin
$UserObject | Add-Member -MemberType NoteProperty -Name ProfilePath -Value $ProfilePath
$UserObject
}
}
catch {
Update-Log "Error while translating $SID to a user name." -Color 'Yellow'
}
}
catch {
Update-Log "Error while translating $($_.PSChildName) to SID." -Color 'Yellow'
}
}
}
function Get-UserProfilePath {
param(
[string]$Domain,
[string]$UserName
)
$UserObject = New-Object System.Security.Principal.NTAccount($Domain, $UserName)
$SID = $UserObject.Translate([System.Security.Principal.SecurityIdentifier])
$User = Get-ItemProperty -Path "Registry::HKey_Local_Machine\Software\Microsoft\Windows NT\CurrentVersion\ProfileList\$($SID.Value)"
$User.ProfileImagePath
}
function Test-IsAdmin {
$UserIdentity = [Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()
if (-not $UserIdentity.IsInRole([Security.Principal.WindowsBuiltInRole] 'Administrator')) {
Update-Log "You are not running this script as Administrator. " -Color 'Yellow' -NoNewLine
Update-Log "Some tasks may fail if launched as Administrator.`n" -Color 'Yellow'
}
}
function Set-SaveDirectory {
param (
[Parameter(Mandatory = $true)]
[ValidateSet('Destination', 'Source')]
[string] $Type
)
# Bring up file explorer so user can select a directory to add
$OpenDirectoryDialog = New-Object Windows.Forms.FolderBrowserDialog
$OpenDirectoryDialog.RootFolder = 'Desktop'
$OpenDirectoryDialog.SelectedPath = $SaveDestinationTextBox.Text
if ($Type -eq 'Destination') {
$OpenDirectoryDialog.SelectedPath = $SaveDestinationTextBox.Text
}
else {
$OpenDirectoryDialog.SelectedPath = $SaveSourceTextBox.Text
}
$OpenDirectoryDialog.ShowDialog() | Out-Null
$SelectedDirectory = $OpenDirectoryDialog.SelectedPath
try {
# If user hits cancel it could cause attempt to add null path, so check that there's something there
if ($SelectedDirectory) {
Update-Log "Changed save directory to [$SelectedDirectory]."
if ($Type -eq 'Destination') {
$SaveDestinationTextBox.Text = $SelectedDirectory
}
else {
$SaveSourceTextBox.Text = $SelectedDirectory
}
}
}
catch {
Update-Log "There was a problem with the directory you chose: $($_.Exception.Message)" -Color Red
}
}
function Add-ExtraDirectory {
# Bring up file explorer so user can select a directory to add
$OpenDirectoryDialog = New-Object Windows.Forms.FolderBrowserDialog
$OpenDirectoryDialog.RootFolder = 'Desktop'
$OpenDirectoryDialog.SelectedPath = 'C:\'
$Result = $OpenDirectoryDialog.ShowDialog()
$SelectedDirectory = $OpenDirectoryDialog.SelectedPath
try {
# If user hits cancel don't add the path
if ($Result -eq 'OK') {
Update-Log "Adding to extra directories: [$SelectedDirectory]."
$ExtraDirectoriesDataGridView.Rows.Add($SelectedDirectory)
}
else {
Update-Log "Add directory action cancelled by user." -Color Yellow
}
}
catch {
Update-Log "There was a problem with the directory you chose: $($_.Exception.Message)" -Color Red
}
}
function Remove-ExtraDirectory {
# Remove selected cell from Extra Directories data grid view
foreach ($CurrentRow in $ExtraDirectoriesDataGridView.SelectedRows) {
Update-Log "Removed [$($CurrentRow.Cells.Value)] from extra directories."
$ExtraDirectoriesDataGridView.Rows.Remove($CurrentRow)
}
}
function Set-Config {
$ExtraDirectoryCount = $ExtraDirectoriesDataGridView.RowCount
if ($ExtraDirectoryCount) {
Update-Log "Including $ExtraDirectoryCount extra directories."
$ExtraDirectoryXML = @"
<!-- This component includes the additional directories selected by the user -->
<component type="Documents" context="System">
<displayName>Additional Folders</displayName>
<role role="Data">
<rules>
<include>
<objectSet>
"@
# Include each directory user has added to the Extra Directories data grid view
$ExtraDirectoriesDataGridView.Rows | ForEach-Object {
$CurrentRowIndex = $_.Index
$Path = $ExtraDirectoriesDataGridView.Item(0, $CurrentRowIndex).Value
$ExtraDirectoryXML += @"
<pattern type=`"File`">$Path\* [*]</pattern>"
"@
}
$ExtraDirectoryXML += @"
</objectSet>
</include>
</rules>
</role>
</component>
"@
}
else {
Update-Log 'No extra directories will be included.'
}
# Add additional file patterns
$ExtraFilesCount = $DefaultExtraFiles.Count
if ($ExtraFilesCount) {
Update-Log "Including $ExtraFilesCount extra file patterns."
$ExtraFilesXML = @"
<!-- This component includes the additional file patterns selected by the user -->
<component type="Documents" context="System">
<displayName>Additional File Patterns</displayName>
<role role="Data">
<rules>
<include>
<objectSet>
"@
# Include each file pattern user has added to the Default Extra Files
$DefaultExtraFiles | ForEach-Object {
$ExtraFile = $_
$ExtraFilesXML += @"
<script>MigXmlHelper.GenerateDrivePatterns ("* [$ExtraFile]", "Fixed")</script>
"@
}
$ExtraFilesXML += @"
</objectSet>
</include>
<exclude>
<objectSet>
"@
# Exclude each file pattern user has added to the Default Extra Files from Users
$DefaultExtraFiles | ForEach-Object {
$ExtraFile = $_
$ExtraFilesXML += @"
<pattern type=`"File`"> C:\Users\* [$ExtraFile]</pattern>
"@
}
$ExtraFilesXML += @"
</objectSet>
</exclude>
</rules>
</role>
</component>
"@
}
else {
Update-Log 'No extra file patterns will be included.'
}
# End add additional file patterns
# Exclude file patterns
$ExcludeFilesCount = $DefaultExcludeFiles.Count
if ($ExcludeFilesCount) {
Update-Log "Excluding $ExcludeFilesCount extra file patterns."
# System Context
$ExcludeFilesXML = @"
<!-- This component excludes the additional file patterns selected by the user -->
<component type="Documents" context="UserandSystem">
<displayName>Additional Excluded File Patterns</displayName>
<role role="Data">
<rules>
<unconditionalExclude>
<objectSet>
"@
# Exclude each file pattern user has added to the Default Exclude Files
$DefaultExcludeFiles | ForEach-Object {
$ExcludeFile = $_
$ExcludeFilesXML += @"
<script>MigXmlHelper.GenerateDrivePatterns ("* [$ExcludeFile]", "Fixed")</script>
"@
}
$ExcludeFilesXML += @"
</objectSet>
</unconditionalExclude>
</rules>
</role>
</component>
"@
}
else {
Update-Log 'No additional file patterns will be excluded.'
}
# End exclude file patterns
Update-Log 'Data to be included:'
foreach ($Control in $InclusionsGroupBox.Controls) { if ($Control.Checked) { Update-Log $Control.Text } }
$ExcludedDataXML = @"
$(
if (-not $IncludePrintersCheckBox.Checked) { "<pattern type=`"File`">%CSIDL_PRINTERS%\* [*]</pattern>`n" }
if (-not $IncludeRecycleBinCheckBox.Checked) { "<pattern type=`"File`">%CSIDL_BITBUCKET%\* [*]</pattern>`n" }
if (-not $IncludeMyDocumentsCheckBox.Checked) {
"<pattern type=`"File`">%CSIDL_MYDOCUMENTS%\* [*]</pattern>`n"
"<pattern type=`"File`">%CSIDL_PERSONAL%\* [*]</pattern>`n"
}
if (-not $IncludeDesktopCheckBox.Checked) {
"<pattern type=`"File`">%CSIDL_DESKTOP%\* [*]</pattern>`n"
"<pattern type=`"File`">%CSIDL_DESKTOPDIRECTORY%\* [*]</pattern>`n"
}
if (-not $IncludeDownloadsCheckBox.Checked) { "<pattern type=`"File`">%CSIDL_DOWNLOADS%\* [*]</pattern>`n" }
if (-not $IncludeFavoritesCheckBox.Checked) { "<pattern type=`"File`">%CSIDL_FAVORITES%\* [*]</pattern>`n" }
if (-not $IncludeMyMusicCheckBox.Checked) { "<pattern type=`"File`">%CSIDL_MYMUSIC%\* [*]</pattern>`n" }
if (-not $IncludeMyPicturesCheckBox.Checked) { "<pattern type=`"File`">%CSIDL_MYPICTURES%\* [*]</pattern>`n" }
if (-not $IncludeMyVideoCheckBox.Checked) { "<pattern type=`"File`">%CSIDL_MYVIDEO%\* [*]</pattern>`n" }
)
"@
$AppDataXML = if ($IncludeAppDataCheckBox.Checked) {
@"
<!-- This component migrates all user app data -->
<component type=`"Documents`" context=`"User`">
<displayName>App Data</displayName>
<paths>
<path type="File">%CSIDL_APPDATA%</path>
</paths>
<role role="Data">
<detects>
<detect>
<condition>MigXmlHelper.DoesObjectExist("File","%CSIDL_APPDATA%")</condition>
</detect>
</detects>
<rules>
<include filter='MigXmlHelper.IgnoreIrrelevantLinks()'>
<objectSet>
<pattern type="File">%CSIDL_APPDATA%\* [*]</pattern>
</objectSet>
</include>
<merge script='MigXmlHelper.DestinationPriority()'>
<objectSet>
<pattern type="File">%CSIDL_APPDATA%\* [*]</pattern>
</objectSet>
</merge>
</rules>
</role>
</component>
"@
}
$LocalAppDataXML = if ($IncludeLocalAppDataCheckBox.Checked) {
@"
<!-- This component migrates all user local app data -->
<component type=`"Documents`" context=`"User`">
<displayName>Local App Data</displayName>
<paths>
<path type="File">%CSIDL_LOCAL_APPDATA%</path>
</paths>
<role role="Data">
<detects>
<detect>
<condition>MigXmlHelper.DoesObjectExist("File","%CSIDL_LOCAL_APPDATA%")</condition>
</detect>
</detects>
<rules>
<include filter='MigXmlHelper.IgnoreIrrelevantLinks()'>
<objectSet>
<pattern type="File">%CSIDL_LOCAL_APPDATA%\* [*]</pattern>
</objectSet>
</include>
<merge script='MigXmlHelper.DestinationPriority()'>
<objectSet>
<pattern type="File">%CSIDL_LOCAL_APPDATA%\* [*]</pattern>
</objectSet>
</merge>
</rules>
</role>
</component>
"@
}
$WallpapersXML = if ($IncludeWallpapersCheckBox.Checked) {
@"
<!-- This component migrates wallpaper settings -->
<component type="System" context="User">
<displayName>Wallpapers</displayName>
<role role="Settings">
<rules>
<include>
<objectSet>
<pattern type="Registry">HKCU\Control Panel\Desktop [Pattern]</pattern>
<pattern type="Registry">HKCU\Control Panel\Desktop [PatternUpgrade]</pattern>
<pattern type="Registry">HKCU\Control Panel\Desktop [TileWallpaper]</pattern>
<pattern type="Registry">HKCU\Control Panel\Desktop [WallPaper]</pattern>
<pattern type="Registry">HKCU\Control Panel\Desktop [WallpaperStyle]</pattern>
<pattern type="Registry">HKCU\Software\Microsoft\Windows\CurrentVersion\Themes [SetupVersion]</pattern>
<pattern type="Registry">HKCU\Software\Microsoft\Internet Explorer\Desktop\General [BackupWallpaper]</pattern>
<pattern type="Registry">HKCU\Software\Microsoft\Internet Explorer\Desktop\General [TileWallpaper]</pattern>
<pattern type="Registry">HKCU\Software\Microsoft\Internet Explorer\Desktop\General [Wallpaper]</pattern>
<pattern type="Registry">HKCU\Software\Microsoft\Internet Explorer\Desktop\General [WallpaperFileTime]</pattern>
<pattern type="Registry">HKCU\Software\Microsoft\Internet Explorer\Desktop\General [WallpaperLocalFileTime]</pattern>
<pattern type="Registry">HKCU\Software\Microsoft\Internet Explorer\Desktop\General [WallpaperStyle]</pattern>
<content filter="MigXmlHelper.ExtractSingleFile(NULL, NULL)">
<objectSet>
<pattern type="Registry">HKCU\Control Panel\Desktop [WallPaper]</pattern>
<pattern type="Registry">HKCU\Software\Microsoft\Internet Explorer\Desktop\General [BackupWallpaper]</pattern>
<pattern type="Registry">HKCU\Software\Microsoft\Internet Explorer\Desktop\General [Wallpaper]</pattern>
</objectSet>
</content>
</objectSet>
</include>
</rules>
</role>
</component>
<!-- This component migrates wallpaper files -->
<component type="Documents" context="System">
<displayName>Move JPG and BMP</displayName>
<role role="Data">
<rules>
<include>
<objectSet>
<pattern type="File"> %windir% [*.bmp]</pattern>
<pattern type="File"> %windir%\web\wallpaper [*.jpg]</pattern>
<pattern type="File"> %windir%\web\wallpaper [*.bmp]</pattern>
</objectSet>
</include>
</rules>
</role>
</component>
"@
}
$ConfigContent = @"
<?xml version="1.0" encoding="UTF-8"?>
<migration urlid="http://www.microsoft.com/migration/1.0/migxmlext/config">
<_locDefinition>
<_locDefault _loc="locNone"/>
<_locTag _loc="locData">displayName</_locTag>
</_locDefinition>
$ExtraDirectoryXML
$ExtraFilesXML
$ExcludeFilesXML
<!-- This component migrates all user data except specified exclusions -->
<component type="Documents" context="User">
<displayName>Documents</displayName>
<role role="Data">
<rules>
<include filter="MigXmlHelper.IgnoreIrrelevantLinks()">
<objectSet>
<script>MigXmlHelper.GenerateDocPatterns ("FALSE","TRUE","FALSE")</script>
</objectSet>
</include>
<exclude filter='MigXmlHelper.IgnoreIrrelevantLinks()'>
<objectSet>
<script>MigXmlHelper.GenerateDocPatterns ("FALSE","FALSE","FALSE")</script>
</objectSet>
</exclude>
<exclude>
<objectSet>
$ExcludedDataXML
</objectSet>
</exclude>
<contentModify script="MigXmlHelper.MergeShellLibraries('TRUE','TRUE')">
<objectSet>
<pattern type="File">*[*.library-ms]</pattern>
</objectSet>
</contentModify>
<merge script="MigXmlHelper.SourcePriority()">
<objectSet>
<pattern type="File">*[*.library-ms]</pattern>
</objectSet>
</merge>
</rules>
</role>
</component>
$AppDataXML
$LocalAppDataXML
$WallpapersXML
</migration>
"@
$Config = "$Destination\Config.xml"
try {
New-Item $Config -ItemType File -Force -ErrorAction Stop | Out-Null
}
catch {
Update-Log "Error creating config file [$Config]: $($_.Exception.Message)" -Color 'Red'
return
}
try {
Set-Content $Config $ConfigContent -ErrorAction Stop
}
catch {
Update-Log "Error while setting config file content: $($_.Exception.Message)" -Color 'Red'
return
}
# Return the path to the config
$Config
}
function Get-USMT {
# Test that USMT binaries are reachable
if (Test-Path $USMTPath) {
$Script:ScanState = "$USMTPath\scanstate.exe"
$Script:LoadState = "$USMTPath\loadstate.exe"
Update-Log "Using [$USMTPath] as path to USMT binaries."
}
else {
Update-Log "Unable to reach USMT binaries. Verify [$USMTPath] exists and restart script.`n" -Color 'Red'
$MigrateButton_OldPage.Enabled = $false
$MigrateButton_NewPage.Enabled = $false
}
}
function Get-USMTResults {
param([string] $ActionType)
if ($PSVersionTable.PSVersion.Major -lt 3) {
# Print back the entire log
$Results = Get-Content "$Destination\$ActionType.log" | Out-String
}
else {
# Get the last 4 lines from the log so we can see the results
$Results = Get-Content "$Destination\$ActionType.log" -Tail 4 | ForEach-Object {
($_.Split(']', 2)[1]).TrimStart()
} | Out-String
}
Update-Log $Results -Color 'Cyan'
if ($ActionType -eq 'load') {
Update-Log 'A reboot is recommended.' -Color 'Yellow'
$EmailSubject = "Migration Load Results of $($OldComputerNameTextBox_NewPage.Text) to $($NewComputerNameTextBox_NewPage.Text)"
}
else {
$EmailSubject = "Migration Save Results of $($OldComputerNameTextBox_OldPage.Text) to $($NewComputerNameTextBox_OldPage.Text)"
}
if ($EmailCheckBox.Checked) {
if ($SMTPConnectionCheckBox.Checked -or (Test-Connection -ComputerName $SMTPServerTextBox.Text -Quiet)) {
$SMTPConnectionCheckBox.Checked = $true
$EmailRecipients = @()
$EmailRecipientsDataGridView.Rows | ForEach-Object {
$CurrentRowIndex = $_.Index
$EmailRecipients += $EmailRecipientsDataGridView.Item(0, $CurrentRowIndex).Value
}
Update-Log "Emailing migration results to: $EmailRecipients"
try {
$SendMailMessageParams = @{
From = $EmailSenderTextBox.Text
To = $EmailRecipients
Subject = $EmailSubject
Body = $LogTextBox.Text
SmtpServer = $SMTPServerTextBox.Text
Attachments = "$Destination\$ActionType.log"
}
Send-MailMessage @SendMailMessageParams
}
catch {
Update-Log "Error occurred sending email: $($_.Exception.Message)" -Color 'Red'
}
}
else {
Update-Log "Unable to send email of results because SMTP server [$($SMTPServerTextBox.Text)] is unreachable." -Color 'Yellow'
}
}
}
function Get-USMTProgress {
param(
[string] $Destination,
[string] $ActionType
)
try {
# Get the most recent entry in the progress log
$LastLine = Get-Content "$Destination\$($ActionType)_progress.log" -Tail 1 -ErrorAction SilentlyContinue | Out-String
Update-Log ($LastLine.Split(',', 4)[3]).TrimStart()
}
catch { Update-Log '.' -NoNewLine }
}
function Get-SaveState {
# Use the migration folder name to get the old computer name
if (Get-ChildItem $SaveSourceTextBox.Text -ErrorAction SilentlyContinue) {
$SaveSource = Get-ChildItem $SaveSourceTextBox.Text | Where-Object { $_.PSIsContainer } |
Sort-Object -Descending -Property { $_.CreationTime } | Select-Object -First 1
if (Test-Path "$($SaveSource.FullName)\USMT\USMT.MIG") {
$Script:UncompressedSource = $false
}
else {
$Script:UncompressedSource = $true
Update-Log -Message "Uncompressed save state detected."
}
$OldComputer = $SaveSource.BaseName
Update-Log -Message "Old computer set to $OldComputer."
}
else {
$OldComputer = 'N/A'
Update-Log -Message "No saved state found at [$($SaveSourceTextBox.Text)]." -Color 'Yellow'
}
$OldComputer
}
function Show-DomainInfo {
# Populate old user data if DomainMigration.txt file exists, otherwise disable group box
if (Test-Path "$MigrationStorePath\$($OldComputerNameTextBox_NewPage.Text)\DomainMigration.txt") {
$OldUser = Get-Content "$MigrationStorePath\$($OldComputerNameTextBox_NewPage.Text)\DomainMigration.txt"
$OldDomainTextBox.Text = $OldUser.Split('\')[0]
$OldUserNameTextBox.Text = $OldUser.Split('\')[1]
}
else {
$CrossDomainMigrationGroupBox.Enabled = $false
$CrossDomainMigrationGroupBox.Hide()
}
}
function Save-UserState {
param(
[switch] $Debug
)
Update-Log "`nBeginning migration..."
# Run scripts before doing actual data migration
$OldComputerScriptsDataGridView.Rows | ForEach-Object {
$ScriptName = $OldComputerScriptsDataGridView.Item(0, $_.Index).Value
$ScriptPath = "$PSScriptRoot\USMT\Scripts\OldComputer\$ScriptName"
Update-Log "Running $ScriptPath"
if (-not $Debug) {
$Result = if ($ScriptPath.EndsWith('ps1')) {
. $ScriptPath
}
else {
Start-Process $ScriptPath -Wait -PassThru
}
Update-Log ($Result | Out-String)
}
}
# If we're saving locally, skip network stuff
if ($SaveRemotelyCheckBox.Checked) {
# If connection hasn't been verfied, test now
if (-not $ConnectionCheckBox_OldPage.Checked) {
$TestComputerConnectionParams = @{
ComputerNameTextBox = $NewComputerNameTextBox_OldPage
ComputerIPTextBox = $NewComputerIPTextBox_OldPage
ConnectionCheckBox = $ConnectionCheckBox_OldPage
}
Test-ComputerConnection @TestComputerConnectionParams
}
# Try and use the IP if the user filled that out, otherwise use the name
if ($NewComputerIPTextBox_OldPage.Text -ne '') {
$NewComputer = $NewComputerIPTextBox_OldPage.Text
}
else {
$NewComputer = $NewComputerNameTextBox_OldPage.Text
}
}
$OldComputer = $OldComputerNameTextBox_OldPage.Text
# After connection has been verified, continue with save state
if ($ConnectionCheckBox_OldPage.Checked -or (-not $SaveRemotelyCheckBox.Checked)) {
Update-Log 'Connection verified, proceeding with migration...'
# Get the selected profiles
if ($RecentProfilesCheckBox.Checked -eq $true) {
Update-Log "All profiles logged into within the last $($RecentProfilesDaysTextBox.Text) days will be saved."
}
elseif ($Script:SelectedProfile) {
Update-Log "Profile(s) selected for save state:"
$Script:SelectedProfile | ForEach-Object { Update-Log $_.UserName }
}
else {
Update-Log "You must select a user profile." -Color 'Red'
return
}
if (-not $SaveRemotelyCheckBox.Checked) {
$Script:Destination = "$($SaveDestinationTextBox.Text)\$OldComputer"
}
else {
# Set destination folder on new computer
try {
$DriveLetter = $MigrationStorePath.Split(':', 2)[0]
$MigrationStorePath = $MigrationStorePath.TrimStart('C:\')
New-Item "\\$NewComputer\$DriveLetter$\$MigrationStorePath" -ItemType Directory -Force | Out-Null
$Script:Destination = "\\$NewComputer\$DriveLetter$\$MigrationStorePath\$OldComputer"
}
catch {
Update-Log "Error while creating migration store [$Destination]: $($_.Exception.Message)" -Color 'Yellow'
return
}
}
# Create destination folder
if (!(Test-Path $Destination)) {
try {
New-Item $Destination -ItemType Directory -Force | Out-Null
}
catch {
Update-Log "Error while creating migration store [$Destination]: $($_.Exception.Message)" -Color 'Yellow'
return
}
}
#Verify that the Destination folder is valid.
if (Test-Path $Destination) {
# If profile is a domain other than $DefaultDomain, save this info to text file
if ($RecentProfilesCheckBox.Checked -eq $false) {
$FullUserName = "$($Script:SelectedProfile.Domain)\$($Script:SelectedProfile.UserName)"
if ($Script:SelectedProfile.Domain -ne $DefaultDomain) {
New-Item "$Destination\DomainMigration.txt" -ItemType File -Value $FullUserName -Force | Out-Null
Update-Log "Text file created with cross-domain information."
}
}
# Clear encryption syntax in case it's already defined.
$EncryptionSyntax = ""
# Determine if Encryption has been requested
if ($Script:EncryptionPasswordSet -eq $True) {
#Disable Compression
$Script:UncompressedSource = $false
$Uncompressed = ''
# Set the syntax for the encryption
$EncryptionKey = """$Script:EncryptionPassword"""
$EncryptionSyntax = "/encrypt /key:$EncryptionKey"
}
#Set the value to continue on error if it was specified above
if ($ContinueOnError -eq $True) {
$ContinueCommand = "/c"
}
if ($ContinueOnError -eq $False) {
$ContinueCommand = ""
}
# Create config syntax for scanstate for custom XMLs.
if ($SelectedXMLS) {
#Create the scanstate syntax line for the config files.
foreach ($ConfigXML in $SelectedXMLS) {
$ConfigXMLPath = """$Script:USMTPath\$ConfigXML"""
$ScanstateConfig += "/i:$ConfigXMLPath "
}
}
# Create config syntax for scanstate for generated XML.
if (!($SelectedXMLS)) {
# Create the scan configuration
Update-Log 'Generating configuration file...'
$Config = Set-Config
$GeneratedConfig = """$Config"""
$ScanStateConfig = "/i:$GeneratedConfig"
}
# Generate parameter for logging
$Logs = "`"/listfiles:$Destination\FilesMigrated.log`" `"/l:$Destination\scan.log`" `"/progress:$Destination\scan_progress.log`""
# Set parameter for whether save state is compressed
if ($UncompressedCheckBox.Checked -eq $true) {
$Uncompressed = '/nocompress'
}
else {
$Uncompressed = ''
}
# Create a string for all users to exclude by default
foreach ($ExcludeProfile in $Script:DefaultExcludeProfile) {
$ExcludeProfile = """$ExcludeProfile"""
$UsersToExclude += "/ue:$ExcludeProfile "
}
# Set the EFS Syntax based on the config.
if ($EFSHandling) {
$EFSSyntax = "/efs:$EFSHandling"
}
# Overwrite existing save state, use volume shadow copy method, exclude all but the selected profile(s)
# Get the selected profiles
if ($RecentProfilesCheckBox.Checked -eq $true) {
$Arguments = "`"$Destination`" $ScanStateConfig /o /vsc $UsersToExclude /uel:$($RecentProfilesDaysTextBox.Text) $EncryptionSyntax $Uncompressed $Logs $EFSSyntax $ContinueCommand"
}
else {
$UsersToInclude += $Script:SelectedProfile | ForEach-Object { "`"/ui:$($_.Domain)\$($_.UserName)`"" }
$Arguments = "`"$Destination`" $ScanStateConfig /o /vsc /ue:* $UsersToExclude $UsersToInclude $EncryptionSyntax $Uncompressed $Logs $EFSSyntax $ContinueCommand "
}
# Begin saving user state to new computer
# Create a value to show in the log in order to obscure the encryption key if one was used.
$LogArguments = $Arguments -Replace '/key:".*"', '/key:(Hidden)'
Update-Log "Command used:"
Update-Log "$ScanState $LogArguments" -Color 'Cyan'
# If we're running in debug mode don't actually start the process
if ($Debug) { return }
Update-Log "Saving state of $OldComputer to $Destination..." -NoNewLine
Start-Process -FilePath $ScanState -ArgumentList $Arguments -Verb RunAs
# Give the process time to start before checking for its existence
Start-Sleep -Seconds 3
# Wait until the save state is complete
try {
$ScanProcess = Get-Process -Name scanstate -ErrorAction Stop
while (-not $ScanProcess.HasExited) {
Get-USMTProgress
Start-Sleep -Seconds 3
}
Update-Log "Complete!" -Color 'Green'
Update-Log 'Results:'
Get-USMTResults -ActionType 'scan'
}
catch {
Update-Log $_.Exception.Message -Color 'Red'
}
}
ELSE {
Update-Log "Error when trying to access [$Destination] Please verify that the user account running the utility has appropriate permissions to the folder.: $($_.Exception.Message)" -Color 'Yellow'
}
}
}
function Restore-UserState {
param(
[switch] $Debug
)
Update-Log "`nBeginning migration..."
# Run scripts before doing actual data migration
$NewComputerScriptsDataGridView.Rows | ForEach-Object {
$ScriptName = $NewComputerScriptsDataGridView.Item(0, $_.Index).Value
$ScriptPath = "$PSScriptRoot\USMT\Scripts\NewComputer\$ScriptName"
Update-Log "Running $ScriptPath"
if (-not $Debug) {
$Result = if ($ScriptPath.EndsWith('ps1')) {
. $ScriptPath
}
else {
Start-Process $ScriptPath -Wait -PassThru
}
Update-Log ($Result | Out-String)
}
}
# If override is enabled, skip network checks
if (-not $OverrideCheckBox.Checked) {
# If connection hasn't been verfied, test now
if (-not $ConnectionCheckBox_NewPage.Checked) {
$TestComputerConnectionParams = @{
ComputerNameTextBox = $OldComputerNameTextBox_NewPage
ComputerIPTextBox = $OldComputerIPTextBox_NewPage
ConnectionCheckBox = $ConnectionCheckBox_NewPage
}
Test-ComputerConnection @TestComputerConnectionParams
}
# Try and use the IP if the user filled that out, otherwise use the name
if ($OldComputerIPTextBox_NewPage.Text -ne '') {
$OldComputer = $OldComputerIPTextBox_NewPage.Text
}
else {
$OldComputer = $OldComputerNameTextBox_NewPage.Text
}
if ($ConnectionCheckBox_NewPage.Checked) {
Update-Log "Connection verified, checking in with $OldComputer..."
# Check in with the old computer and don't start until the save is complete
if (Get-Process -Name scanstate -ComputerName $OldComputer -ErrorAction SilentlyContinue) {
Update-Log "Waiting on $OldComputer to complete save state..."
while (Get-Process -Name scanstate -ComputerName $OldComputer -ErrorAction SilentlyContinue) {
Get-USMTProgress
Start-Sleep -Seconds 1
}
}
else {
Update-Log "Save state process on $OldComputer is complete. Proceeding with migration."
}
}
else {
Update-Log "Unable to verify connection with $OldComputer. Migration cancelled." -Color 'Red'
return
}
}
else {
$OldComputer = $OldComputerNameTextBox_NewPage.Text
Update-Log "User has verified the save state process on $OldComputer is already completed. Proceeding with migration."
}
$OldComputerName = $OldComputerNameTextBox_NewPage.Text
# Get the location of the save state data
$Script:Destination = "$($SaveSourceTextBox.Text)\$OldComputerName"
# Check that the save state data exists
if (-not (Test-Path $Destination)) {
Update-Log "No saved state found at [$Destination]. Migration cancelled." -Color 'Red'
return
}
# Clear decryption syntax in case it's already defined.
$DecryptionSyntax = ""
# Determine if Encryption has been requested
if ($Script:EncryptionPasswordSet -eq $True) {
# Disable Compression
$Script:UncompressedSource = $false
$Uncompressed = ''
# Set the syntax for the encryption
$DecryptionKey = """$Script:EncryptionPassword"""
$DecryptionSyntax = "/decrypt /key:$DecryptionKey"
}
# Set the value to continue on error if it was specified above
if ($ContinueOnError -eq $True) {
$ContinueCommand = "/c"
}
if ($ContinueOnError -eq $false) {
$ContinueCommand = ""
}
# Set the value for the Config file if one exists.
if (Test-Path "$Destination\Config.xml") {
$LoadStateConfigFile = """$Destination\Config.xml"""
$LoadStateConfig = "/i:$LoadStateConfigFile"
}
# Generate arguments for load state process
$Logs = "`"/l:$Destination\load.log`" `"/progress:$Destination\load_progress.log`""
# Set parameter for whether save state is compressed
if ($UncompressedSource -eq $true) {
$Uncompressed = '/nocompress'
}
else {