-
Notifications
You must be signed in to change notification settings - Fork 2
/
CopyTo-OneDrive.ps1
530 lines (470 loc) · 29.2 KB
/
CopyTo-OneDrive.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
<#
.DESCRIPTION
###############Disclaimer#####################################################
THIS CODE IS PROVIDED AS IS WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
###############Disclaimer#####################################################
What this script does:
1) Copy my HomeDrive folder to my local OneDrive Sync Folder
2) Redirect and Copy My Documents, Desktop, Pictures, Videos, Music, and Favorites to OneDrive location
3) Perform both Steps #1 and #2
4) Revert the Folder Redirection changes in Step #2
5) Exit this script
Variables you can update (to change any of these settings check the Variables region):
1) Exclude certain file types. The script by default excludes .PST files and won't copy those to the OneDrive location
2) Exclude file paths longer than 256 chars
3) Exclude files olders than X date
4) Exclude files larger than X size
Robocopy is used to copy the files to the local OneDrive for Business folder.
Questions: [email protected]
#>
#region Functions
Function Write-LogEntry {
param(
[string] $LogName ,
[string] $LogEntryText,
[string] $ForegroundColor
)
if ($LogName -NotLike $Null) {
# log the date and time in the text file along with the data passed
"$([DateTime]::Now.ToShortDateString()) $([DateTime]::Now.ToShortTimeString()) : $LogEntryText" | Out-File -FilePath $LogName -append;
if ($ForeGroundColor -NotLike $null) {
# for testing i pass the ForegroundColor parameter to act as a switch to also write to the shell console
write-host $LogEntryText -ForegroundColor $ForeGroundColor
}
}
}
Function Sync-ThisFolder {
<#
Use RoboCopy to copy the files in the user's file share to their local OneDrive for Business folder.
-------------------------------------------------------------------------------
ROBOCOPY :: Robust File Copy for Windows
-------------------------------------------------------------------------------
source :: Source Directory (drive:\path or \\server\share\path).
destination :: Destination Dir (drive:\path or \\server\share\path).
file :: File(s) to copy (names/wildcards: default is "*.*").
/E :: copy subdirectories, including Empty ones.
/DCOPY:copyflag[s] :: what to COPY for directories (default is /DCOPY:DA).
(copyflags : D=Data, A=Attributes, T=Timestamps).
/COPY:copyflag[s] :: what to COPY for files (default is /COPY:DAT).
(copyflags : D=Data, A=Attributes, T=Timestamps).
(S=Security=NTFS ACLs, O=Owner info, U=aUditing info).
/XJ :: eXclude Junction points. (normally included by default).
/XF file [file]... :: eXclude Files matching given names/paths/wildcards.
/XD dirs [dirs]... :: eXclude Directories matching given names/paths.
/R:n :: number of Retries on failed copies: default 1 million.
/W:n :: Wait time between retries: default is 30 seconds.
/256 :: turn off very long path (> 256 characters) support.
/MAX:n :: MAXimum file size - exclude files bigger than n bytes.
/MAXAGE:n :: MAXimum file AGE - exclude files older than n days/date.
/MT[:n] :: Do multi-threaded copies with n threads (default 8).
n must be at least 1 and not greater than 128.
This option is incompatible with the /IPG and /EFSRAW options.
Redirect output using /LOG option for better performance.
/V :: produce Verbose output, showing skipped files.
/ETA :: show Estimated Time of Arrival of copied files.
/LOG+:file :: output status to LOG file (append to existing log).
#>
param(
[string]$SourcePath, # = "C:\Users\administrator\Desktop\migrateMe", # = (get-childitem ENV:HomeDrive).Value,
[string]$TargetPath, # = "C:\Users\administrator\Desktop\migrateMe"
[string]$SubFolderName = "_MIGRATED",
[string]$ExcludeFileTypes = "/xf *.pst *.docx", #Example: "/xf *.pst *.docx"
[string]$ExcludeLongPaths, #Example: "/256"
[string]$ExcludeFilesLargerThanXBytes, #Example: "/MAX:2000"
[string]$ExcludeFilesOlderThan, #Example: "/MAXAGE:20170101"
[switch]$SkipConfirm
)
Begin{
try{
""
#Functions
Function Select-FolderDialog{
param(
[string]$Description="Select folder to copy to your local OneDrive sync folder",
[string]$RootFolder="Desktop"
)
[System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") | Out-Null
$objForm = New-Object System.Windows.Forms.FolderBrowserDialog
$objForm.Rootfolder = $RootFolder
$objForm.Description = $Description
$Show = $objForm.ShowDialog()
If ($Show -eq "OK") {
Return $objForm.SelectedPath
}
Else{
Write-Error "Operation cancelled by user."
}
}
Function Get-RoboFolderSizeInternal {
[CmdletBinding()]
param(
# Paths to report size, file count, dir count, etc. for.
[string[]] $Path,
[int] $Precision = 4)
begin {
if (-not (Get-Command -Name robocopy -ErrorAction SilentlyContinue)) {
Write-Warning -Message "Fallback to robocopy failed because robocopy.exe could not be found. Path '$p'. $([datetime]::Now)."
return
}
}
process {
foreach ($p in $Path) {
Write-Verbose -Message "Processing path '$p' with Get-RoboFolderSizeInternal. $([datetime]::Now)."
$RoboCopyArgs = @("/L","/S","/NJH","/BYTES","/FP","/NC","/NDL","/TS","/XJ","/R:0","/W:0","/MT:$RoboThreadCount")
[datetime] $StartedTime = [datetime]::Now
[string] $Summary = robocopy $p NULL $RoboCopyArgs | Select-Object -Last 8
[datetime] $EndedTime = [datetime]::Now
[regex] $HeaderRegex = '\s+Total\s*Copied\s+Skipped\s+Mismatch\s+FAILED\s+Extras'
[regex] $DirLineRegex = 'Dirs\s*:\s*(?<DirCount>\d+)(?:\s+\d+){3}\s+(?<DirFailed>\d+)\s+\d+'
[regex] $FileLineRegex = 'Files\s*:\s*(?<FileCount>\d+)(?:\s+\d+){3}\s+(?<FileFailed>\d+)\s+\d+'
[regex] $BytesLineRegex = 'Bytes\s*:\s*(?<ByteCount>\d+)(?:\s+\d+){3}\s+(?<BytesFailed>\d+)\s+\d+'
[regex] $TimeLineRegex = 'Times\s*:\s*(?<TimeElapsed>\d+).*'
[regex] $EndedLineRegex = 'Ended\s*:\s*(?<EndedTime>.+)'
if ($Summary -match "$HeaderRegex\s+$DirLineRegex\s+$FileLineRegex\s+$BytesLineRegex\s+$TimeLineRegex\s+$EndedLineRegex") {
New-Object PSObject -Property @{
Path = $p
TotalBytes = [decimal] $Matches['ByteCount']
TotalMBytes = [math]::Round(([decimal] $Matches['ByteCount'] / 1MB), $Precision)
TotalGBytes = [math]::Round(([decimal] $Matches['ByteCount'] / 1GB), $Precision)
BytesFailed = [decimal] $Matches['BytesFailed']
DirCount = [decimal] $Matches['DirCount']
FileCount = [decimal] $Matches['FileCount']
DirFailed = [decimal] $Matches['DirFailed']
FileFailed = [decimal] $Matches['FileFailed']
TimeElapsed = [math]::Round([decimal] ($EndedTime - $StartedTime).TotalSeconds, $Precision)
StartedTime = $StartedTime
EndedTime = $EndedTime
} | Select-Object -Property Path, TotalBytes, TotalMBytes, TotalGBytes, DirCount, FileCount, DirFailed, FileFailed, TimeElapsed, StartedTime, EndedTime
}
else {
Write-Warning -Message "Path '$p' output from robocopy was not in an expected format."
}
}
}
}
#Variables
$elapsed = [System.Diagnostics.Stopwatch]::StartNew()
Write-Host "Pre-flight Check" -ForegroundColor Yellow
$robocopy = "C:\Windows\System32\Robocopy.exe"
If(!$TargetPath){
#$key = "HKCU:\Software\Microsoft\OneDrive\Accounts\Business1"
#$oneDriveFolder = (Get-ItemProperty -Path $key -Name UserFolder).UserFolder
$oneDriveFolder = $ENV:OneDrive
If(!$oneDriveFolder){throw "Local OneDrive Sync Folder not found. Make sure the sync client is installed."}
$SubFolderName = "\$SubFolderName"
$TargetPath = $oneDriveFolder + $SubFolderName
}
If(!$SourcePath){
$sourcePath = Select-FolderDialog -Description "Choose the folder you want to copy to your local OneDrive sync folder"
}
Else{
If(!$SkipConfirm){
$confirmEntry = Read-Host "Copy $SourcePath to $targetPath (Y/N)"
If($confirmEntry -ne "Y"){
throw "Choose the correct folder you would like to copy to your OneDrive sync folder"
}
}
}
If(!$SourcePath){throw "No folder selected to copy to Sync Folder"}
$sourcePath = '"' + $sourcePath + '"'
$TargetPath = '"' + $TargetPath + '"'
$argumentList = $sourcePath + " " + $targetPath + " " + ("$excludeFileTypes $ExcludeLongPaths $ExcludeFilesLargerThanXBytes $ExcludeFilesOlderThan /tee /e /XJ /DCOPY:T /copy:dt /r:2 /w:2 /V /ETA /unilog+:$log").Split(" ",[System.StringSplitOptions]::RemoveEmptyEntries)
#Check source size and make sure there's enough space
$sourceInfo = Get-RoboFolderSizeInternal -Path $SourcePath -Precision 2
$SourceSize = $sourceInfo | select -ExpandProperty TotalMBytes
$drive = Get-PSDrive C | Select-Object Used,Free
$freeSpace = "{0:N2}" -f ($drive.Free /1MB )
If($SourceSize -gt $freeSpace){
throw "Not enough free space available in your local drive. Source Size = $SourceSize MB | Local Free Space = $freeSpace MB "
exit
}
Write-Host "Pre-flight Complete" -ForegroundColor Yellow
""
}
catch{
Write-Host $_ -ForegroundColor Red
""
exit
}
}
Process{
try{
Start-Process -FilePath $robocopy -ArgumentList $argumentList -NoNewWindow -Wait
}
catch{
Write-LogEntry -LogName:$Log -LogEntryText "Ran into an issue: $_" -ForegroundColor Red
}
}
End{
Write-Host "Total Elapsed Time: $($elapsed.Elapsed.ToString())" -ForegroundColor Yellow
Write-Host "Log File: $($log)" -ForegroundColor Yellow
}
}
Function Revert-KnownFolderChanges{
try{
$Key1 = "$PSScriptRoot\UserShellFolders.reg"
$Key2 = "$PSScriptRoot\ShellFolders.reg"
Reg import $Key1 | Out-Null
Reg import $Key2 | Out-Null
}
catch{
Write-LogEntry -LogName:$Log -LogEntryText "Unable to revert known folder changes: $_" -ForegroundColor Red
exit
}
}
Function Set-KnownFolderPath {
#https://stackoverflow.com/questions/25709398/set-location-of-special-folders-with-powershell
#https://gist.github.com/semenko/49a28675e4aae5c8be49b83960877ac5
<#
.SYNOPSIS
Sets a known folder's path using SHSetKnownFolderPath.
.PARAMETER Folder
The known folder whose path to set.
.PARAMETER Path
The path.
#>
Param (
[Parameter(Mandatory = $true)]
[ValidateSet('AddNewPrograms', 'AdminTools', 'AppUpdates', 'CDBurning', 'ChangeRemovePrograms', 'CommonAdminTools', 'CommonOEMLinks', 'CommonPrograms', 'CommonStartMenu', 'CommonStartup', 'CommonTemplates', 'ComputerFolder', 'ConflictFolder', 'ConnectionsFolder', 'Contacts', 'ControlPanelFolder', 'Cookies', 'Desktop', 'Documents', 'Downloads', 'Favorites', 'Fonts', 'Games', 'GameTasks', 'History', 'InternetCache', 'InternetFolder', 'Links', 'LocalAppData', 'LocalAppDataLow', 'LocalizedResourcesDir', 'Music', 'NetHood', 'NetworkFolder', 'OriginalImages', 'PhotoAlbums', 'Pictures', 'Playlists', 'PrintersFolder', 'PrintHood', 'Profile', 'ProgramData', 'ProgramFiles', 'ProgramFilesX64', 'ProgramFilesX86', 'ProgramFilesCommon', 'ProgramFilesCommonX64', 'ProgramFilesCommonX86', 'Programs', 'Public', 'PublicDesktop', 'PublicDocuments', 'PublicDownloads', 'PublicGameTasks', 'PublicMusic', 'PublicPictures', 'PublicVideos', 'QuickLaunch', 'Recent', 'RecycleBinFolder', 'ResourceDir', 'RoamingAppData', 'SampleMusic', 'SamplePictures', 'SamplePlaylists', 'SampleVideos', 'SavedGames', 'SavedSearches', 'SEARCH_CSC', 'SEARCH_MAPI', 'SearchHome', 'SendTo', 'SidebarDefaultParts', 'SidebarParts', 'StartMenu', 'Startup', 'SyncManagerFolder', 'SyncResultsFolder', 'SyncSetupFolder', 'System', 'SystemX86', 'Templates', 'TreeProperties', 'UserProfiles', 'UsersFiles', 'Videos', 'Windows')]
[string]$KnownFolder,
[Parameter(Mandatory = $true)]
[string]$Path
)
# Define known folder GUIDs
$KnownFolders = @{
'AddNewPrograms' = 'de61d971-5ebc-4f02-a3a9-6c82895e5c04';
'AdminTools' = '724EF170-A42D-4FEF-9F26-B60E846FBA4F';
'AppUpdates' = 'a305ce99-f527-492b-8b1a-7e76fa98d6e4';
'CDBurning' = '9E52AB10-F80D-49DF-ACB8-4330F5687855';
'ChangeRemovePrograms' = 'df7266ac-9274-4867-8d55-3bd661de872d';
'CommonAdminTools' = 'D0384E7D-BAC3-4797-8F14-CBA229B392B5';
'CommonOEMLinks' = 'C1BAE2D0-10DF-4334-BEDD-7AA20B227A9D';
'CommonPrograms' = '0139D44E-6AFE-49F2-8690-3DAFCAE6FFB8';
'CommonStartMenu' = 'A4115719-D62E-491D-AA7C-E74B8BE3B067';
'CommonStartup' = '82A5EA35-D9CD-47C5-9629-E15D2F714E6E';
'CommonTemplates' = 'B94237E7-57AC-4347-9151-B08C6C32D1F7';
'ComputerFolder' = '0AC0837C-BBF8-452A-850D-79D08E667CA7';
'ConflictFolder' = '4bfefb45-347d-4006-a5be-ac0cb0567192';
'ConnectionsFolder' = '6F0CD92B-2E97-45D1-88FF-B0D186B8DEDD';
'Contacts' = '56784854-C6CB-462b-8169-88E350ACB882';
'ControlPanelFolder' = '82A74AEB-AEB4-465C-A014-D097EE346D63';
'Cookies' = '2B0F765D-C0E9-4171-908E-08A611B84FF6';
'Desktop' = 'B4BFCC3A-DB2C-424C-B029-7FE99A87C641';
'Documents' = 'FDD39AD0-238F-46AF-ADB4-6C85480369C7';
'Downloads' = '374DE290-123F-4565-9164-39C4925E467B';
'Favorites' = '1777F761-68AD-4D8A-87BD-30B759FA33DD';
'Fonts' = 'FD228CB7-AE11-4AE3-864C-16F3910AB8FE';
'Games' = 'CAC52C1A-B53D-4edc-92D7-6B2E8AC19434';
'GameTasks' = '054FAE61-4DD8-4787-80B6-090220C4B700';
'History' = 'D9DC8A3B-B784-432E-A781-5A1130A75963';
'InternetCache' = '352481E8-33BE-4251-BA85-6007CAEDCF9D';
'InternetFolder' = '4D9F7874-4E0C-4904-967B-40B0D20C3E4B';
'Links' = 'bfb9d5e0-c6a9-404c-b2b2-ae6db6af4968';
'LocalAppData' = 'F1B32785-6FBA-4FCF-9D55-7B8E7F157091';
'LocalAppDataLow' = 'A520A1A4-1780-4FF6-BD18-167343C5AF16';
'LocalizedResourcesDir' = '2A00375E-224C-49DE-B8D1-440DF7EF3DDC';
'Music' = '4BD8D571-6D19-48D3-BE97-422220080E43';
'NetHood' = 'C5ABBF53-E17F-4121-8900-86626FC2C973';
'NetworkFolder' = 'D20BEEC4-5CA8-4905-AE3B-BF251EA09B53';
'OriginalImages' = '2C36C0AA-5812-4b87-BFD0-4CD0DFB19B39';
'PhotoAlbums' = '69D2CF90-FC33-4FB7-9A0C-EBB0F0FCB43C';
'Pictures' = '33E28130-4E1E-4676-835A-98395C3BC3BB';
'Playlists' = 'DE92C1C7-837F-4F69-A3BB-86E631204A23';
'PrintersFolder' = '76FC4E2D-D6AD-4519-A663-37BD56068185';
'PrintHood' = '9274BD8D-CFD1-41C3-B35E-B13F55A758F4';
'Profile' = '5E6C858F-0E22-4760-9AFE-EA3317B67173';
'ProgramData' = '62AB5D82-FDC1-4DC3-A9DD-070D1D495D97';
'ProgramFiles' = '905e63b6-c1bf-494e-b29c-65b732d3d21a';
'ProgramFilesX64' = '6D809377-6AF0-444b-8957-A3773F02200E';
'ProgramFilesX86' = '7C5A40EF-A0FB-4BFC-874A-C0F2E0B9FA8E';
'ProgramFilesCommon' = 'F7F1ED05-9F6D-47A2-AAAE-29D317C6F066';
'ProgramFilesCommonX64' = '6365D5A7-0F0D-45E5-87F6-0DA56B6A4F7D';
'ProgramFilesCommonX86' = 'DE974D24-D9C6-4D3E-BF91-F4455120B917';
'Programs' = 'A77F5D77-2E2B-44C3-A6A2-ABA601054A51';
'Public' = 'DFDF76A2-C82A-4D63-906A-5644AC457385';
'PublicDesktop' = 'C4AA340D-F20F-4863-AFEF-F87EF2E6BA25';
'PublicDocuments' = 'ED4824AF-DCE4-45A8-81E2-FC7965083634';
'PublicDownloads' = '3D644C9B-1FB8-4f30-9B45-F670235F79C0';
'PublicGameTasks' = 'DEBF2536-E1A8-4c59-B6A2-414586476AEA';
'PublicMusic' = '3214FAB5-9757-4298-BB61-92A9DEAA44FF';
'PublicPictures' = 'B6EBFB86-6907-413C-9AF7-4FC2ABF07CC5';
'PublicVideos' = '2400183A-6185-49FB-A2D8-4A392A602BA3';
'QuickLaunch' = '52a4f021-7b75-48a9-9f6b-4b87a210bc8f';
'Recent' = 'AE50C081-EBD2-438A-8655-8A092E34987A';
'RecycleBinFolder' = 'B7534046-3ECB-4C18-BE4E-64CD4CB7D6AC';
'ResourceDir' = '8AD10C31-2ADB-4296-A8F7-E4701232C972';
'RoamingAppData' = '3EB685DB-65F9-4CF6-A03A-E3EF65729F3D';
'SampleMusic' = 'B250C668-F57D-4EE1-A63C-290EE7D1AA1F';
'SamplePictures' = 'C4900540-2379-4C75-844B-64E6FAF8716B';
'SamplePlaylists' = '15CA69B3-30EE-49C1-ACE1-6B5EC372AFB5';
'SampleVideos' = '859EAD94-2E85-48AD-A71A-0969CB56A6CD';
'SavedGames' = '4C5C32FF-BB9D-43b0-B5B4-2D72E54EAAA4';
'SavedSearches' = '7d1d3a04-debb-4115-95cf-2f29da2920da';
'SEARCH_CSC' = 'ee32e446-31ca-4aba-814f-a5ebd2fd6d5e';
'SEARCH_MAPI' = '98ec0e18-2098-4d44-8644-66979315a281';
'SearchHome' = '190337d1-b8ca-4121-a639-6d472d16972a';
'SendTo' = '8983036C-27C0-404B-8F08-102D10DCFD74';
'SidebarDefaultParts' = '7B396E54-9EC5-4300-BE0A-2482EBAE1A26';
'SidebarParts' = 'A75D362E-50FC-4fb7-AC2C-A8BEAA314493';
'StartMenu' = '625B53C3-AB48-4EC1-BA1F-A1EF4146FC19';
'Startup' = 'B97D20BB-F46A-4C97-BA10-5E3608430854';
'SyncManagerFolder' = '43668BF8-C14E-49B2-97C9-747784D784B7';
'SyncResultsFolder' = '289a9a43-be44-4057-a41b-587a76d7e7f9';
'SyncSetupFolder' = '0F214138-B1D3-4a90-BBA9-27CBC0C5389A';
'System' = '1AC14E77-02E7-4E5D-B744-2EB1AE5198B7';
'SystemX86' = 'D65231B0-B2F1-4857-A4CE-A8E7C6EA7D27';
'Templates' = 'A63293E8-664E-48DB-A079-DF759E0509F7';
'TreeProperties' = '5b3749ad-b49f-49c1-83eb-15370fbd4882';
'UserProfiles' = '0762D272-C50A-4BB0-A382-697DCD729B80';
'UsersFiles' = 'f3ce0f7c-4901-4acc-8648-d5d44b04ef8f';
'Videos' = '18989B1D-99B5-455B-841C-AB7C74E4DDFC';
'Windows' = 'F38BF404-1D43-42F2-9305-67DE0B28FC23';
}
# Define SHSetKnownFolderPath if it hasn't been defined already
$Type = ([System.Management.Automation.PSTypeName]'KnownFolders').Type
if (-not $Type) {
$Signature = @'
[DllImport("shell32.dll")]
public extern static int SHSetKnownFolderPath(ref Guid folderId, uint flags, IntPtr token, [MarshalAs(UnmanagedType.LPWStr)] string path);
'@
$Type = Add-Type -MemberDefinition $Signature -Name 'KnownFolders' -Namespace 'SHSetKnownFolderPath' -PassThru
}
# Validate the path
if (Test-Path $Path -PathType Container) {
# Call SHSetKnownFolderPath
return $Type::SHSetKnownFolderPath([ref]$KnownFolders[$KnownFolder], 0, 0, $Path)
} else {
throw New-Object System.IO.DirectoryNotFoundException "Could not find part of the path $Path."
}
}
Function RedirectAndCopy-KnownFolders{
try{
#Backup Regkeys
Write-LogEntry -LogName:$Log -LogEntryText "Backing up registry keys before changes" -ForegroundColor White
$key1 = "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders"
$key2 = "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders"
$outKey1 = "$PSScriptRoot\UserShellFolders.reg"
$outKey2 = "$PSScriptRoot\ShellFolders.reg"
Reg export $key1 $outKey1 /y | Out-Null
Reg export $key2 $outKey2 /y | Out-Null
#Variables
$oneDriveFolder = $ENV:OneDrive
$SubFolderName = "\_MIGRATED-$($env:COMPUTERNAME)"
$targetPath = $oneDriveFolder + $SubFolderName
#Create folders in OneDrive location
Write-LogEntry -LogName:$Log -LogEntryText "Create respective folders in the OneDrive Location here: $targetPath" -ForegroundColor White
$desktopPath = "$targetPath\Desktop"
New-Item -Force -ItemType directory -Path $desktopPath | Out-Null
$docsPath = "$targetPath\My Documents"
New-Item -Force -ItemType directory -Path $docsPath | Out-Null
$picturesPath = "$targetPath\Pictures"
New-Item -Force -ItemType directory -Path $picturesPath | Out-Null
$videosPath = "$targetPath\Videos"
New-Item -Force -ItemType directory -Path $videosPath | Out-Null
$musicPath = "$targetPath\Music"
New-Item -Force -ItemType directory -Path $musicPath | Out-Null
$favesPath = "$targetPath\Favorites"
New-Item -Force -ItemType directory -Path $favesPath | Out-Null
#Desktop
Write-LogEntry -LogName:$Log -LogEntryText "Redirect Desktop to: $desktopPath" -ForegroundColor White
Set-KnownFolderPath -KnownFolder Desktop -Path $desktopPath | Out-Null
#My Documents
Write-LogEntry -LogName:$Log -LogEntryText "Redirect Documents to: $docsPath" -ForegroundColor White
Set-KnownFolderPath -KnownFolder Documents -Path $docsPath | Out-Null
#Pictures
Write-LogEntry -LogName:$Log -LogEntryText "Redirect Pictures to: $picturesPath" -ForegroundColor White
Set-KnownFolderPath -KnownFolder Pictures -Path $picturesPath | Out-Null
#Videos
Write-LogEntry -LogName:$Log -LogEntryText "Redirect Videos to: $videosPath" -ForegroundColor White
Set-KnownFolderPath -KnownFolder Videos -Path $videosPath | Out-Null
#Music
Write-LogEntry -LogName:$Log -LogEntryText "Redirect Music to: $musicPath" -ForegroundColor White
Set-KnownFolderPath -KnownFolder Music -Path $musicPath | Out-Null
#Favorites
Write-LogEntry -LogName:$Log -LogEntryText "Redirect Favorites to: $favesPath" -ForegroundColor White
Set-KnownFolderPath -KnownFolder Favorites -Path $favesPath | Out-Null
}
catch{
Write-LogEntry -LogName:$Log -LogEntryText "Ran into an issue when redirecting the folders: $_"
throw "Ran into an issue when redirecting the folders: $_"
exit
}
try{
#Copy the content in those known folders to the local OneDrive sync folder
Write-LogEntry -LogName:$Log -LogEntryText "Copying the files in the above folders to the local OneDrive Sync Folder" -ForegroundColor White
Sync-ThisFolder -SourcePath "$Env:UserProfile\Desktop" -TargetPath $desktopPath -SkipConfirm
Sync-ThisFolder -SourcePath "$Env:UserProfile\Documents" -TargetPath $docsPath -SkipConfirm
Sync-ThisFolder -SourcePath "$Env:UserProfile\Pictures" -TargetPath $picturesPath -SkipConfirm
Sync-ThisFolder -SourcePath "$Env:UserProfile\Videos" -TargetPath $videosPath -SkipConfirm
Sync-ThisFolder -SourcePath "$Env:UserProfile\Music" -TargetPath $musicPath -SkipConfirm
Sync-ThisFolder -SourcePath "$Env:UserProfile\Favorites" -TargetPath $favesPath -SkipConfirm
}
catch{
Write-LogEntry -LogName:$Log -LogEntryText "Ran into an issue copying folder content to the local OneDrive sync location: $_"
}
}
#endregion Functions
#region MAIN
Clear-Host
#Preflight Check
If($host.version.major -lt 3){
throw "Powershell V3+ is required. Contact your administrator"
}
#region Variables
$yyyyMMdd = Get-Date -Format 'yyyyMMdd'
$computer = $env:COMPUTERNAME
$user = $env:USERNAME
$log = "$PSScriptRoot\CopyTo-OneDrive-$yyyyMMdd.log"
Write-LogEntry -LogName:$Log -LogEntryText "User: $user Computer: $computer" -foregroundcolor Yellow
$copysettingSubFolderName = "_MIGRATED"
$copysettingExcludeFileTypes = "/xf *.pst", #Example: "/xf *.pst *.bak"
$copysettingExcludeLongPaths #Example: "/256"
$copysettingExcludeFilesLargerThanXBytes #Example: "/MAX:2000"
$copysettingExcludeFilesOlderThan #Example: "/MAXAGE:20170101"
#endregion Variables
[string] $menu = @'
******************************************************************
Copy/Sync Content to OneDrive for Business
******************************************************************
Please select an option from the list below:
1) Copy my HomeDrive folder to my local OneDrive Sync Folder
2) Redirect and Copy My Documents, Desktop, Pictures, Videos, Music, and Favorites to OneDrive location
3) Perform both Steps #1 and #2
4) Revert the Folder Redirection changes in Step #2
5) Exit this script
Select an option.. [1-5]?
'@
Do {
if ($opt) {"";Write-LogEntry -LogName:$Log -LogEntryText "Last command: $opt" -foregroundcolor Yellow}
$opt = Read-Host $menu
switch ($opt) {
1 { # Copy folder to OneDrive sync location
Write-LogEntry -LogName:$Log -LogEntryText "Selected option 1"
Sync-ThisFolder -SubFolderName $copysettingSubFolderName -ExcludeFileTypes $copysettingExcludeFileTypes -ExcludeLongPaths $copysettingExcludeLongPaths -ExcludeFilesLargerThanXBytes $copysettingExcludeFilesLargerThanXBytes -ExcludeFilesOlderThan $copysettingExcludeFilesOlderThan
Write-LogEntry -LogName:$Log -LogEntryText "Finished copying folder to OneDrive sync location." -ForegroundColor Green
}
2 { # Redirect My Documents folders and copy content to the sync client folder
Write-LogEntry -LogName:$Log -LogEntryText "Selected option 2"
RedirectAndCopy-KnownFolders
Write-LogEntry -LogName:$Log -LogEntryText "Finished redirecting known folders and copying content to the OneDrive sync location." -ForegroundColor Green
}
3 { # Do both #1 and #2
Write-LogEntry -LogName:$Log -LogEntryText "Selected option 3"
Sync-ThisFolder -SubFolderName $copysettingSubFolderName -ExcludeFileTypes $copysettingExcludeFileTypes -ExcludeLongPaths $copysettingExcludeLongPaths -ExcludeFilesLargerThanXBytes $copysettingExcludeFilesLargerThanXBytes -ExcludeFilesOlderThan $copysettingExcludeFilesOlderThan
Write-LogEntry -LogName:$Log -LogEntryText "Finished copying folder to OneDrive sync location." -ForegroundColor Green
RedirectAndCopy-KnownFolders
Write-LogEntry -LogName:$Log -LogEntryText "Finished redirecting known folders and copying content to the OneDrive sync location." -ForegroundColor Green
}
4 { # Revert redirection to out of the box
Write-LogEntry -LogName:$Log -LogEntryText "Selected option 4"
Revert-KnownFolderChanges
Write-LogEntry -LogName:$Log -LogEntryText "Finished reverting known folder changes." -ForegroundColor Green
}
5 { # Exit
Write-LogEntry -LogName:$Log -LogEntryText "Selected option 5"
Write-Host "Exiting..."
}
default {Write-Host "You haven't selected any of the available options."}
}
} while ($opt -ne 5)
#endregion MAIN