-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathInsaneMove.ps1
737 lines (647 loc) · 21.9 KB
/
InsaneMove.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
<#
.SYNOPSIS
Insane Move - Copy sites to Office 365 in parallel. ShareGate Insane Mode times ten!
.DESCRIPTION
Copy SharePoint site collections to Office 365 in parallel. CSV input list of source/destination URLs. XML with general preferences.
Comments and suggestions always welcome! [email protected] or @spjeff
.NOTES
File Name : InsaneMove.ps1
Author : Jeff Jones - @spjeff
Version : 0.41
Last Modified : 01-24-2016
.LINK
Source Code
http://www.github.com/spjeff/insanemove
#>
[CmdletBinding()]
param (
[Parameter(Mandatory=$false, ValueFromPipeline=$false, HelpMessage='CSV list of source and destination SharePoint site URLs to copy to Office 365.')]
[string]$fileCSV,
[Parameter(Mandatory=$false, ValueFromPipeline=$false, HelpMessage='Verify all Office 365 site collections. Prep step before real migration.')]
[Alias("v")]
[switch]$verifyCloudSites = $false,
[Parameter(Mandatory=$false, ValueFromPipeline=$false, HelpMessage='Copy incremental changes only. http://help.share-gate.com/article/443-incremental-copy-copy-sharepoint-content')]
[Alias("i")]
[switch]$incremental = $false,
[Parameter(Mandatory=$false, ValueFromPipeline=$false, HelpMessage='Measure size of site collections in GB.')]
[Alias("m")]
[switch]$measure = $false,
[Parameter(Mandatory=$false, ValueFromPipeline=$false, HelpMessage='Send email notifications with summary of migration batch progress.')]
[Alias("e")]
[switch]$email = $false,
[Parameter(Mandatory=$false, ValueFromPipeline=$false, HelpMessage='Lock sites read-only.')]
[Alias("ro")]
[switch]$readOnly = $false,
[Parameter(Mandatory=$false, ValueFromPipeline=$false, HelpMessage='Unlock sites read-write.')]
[Alias("rw")]
[switch]$readWrite = $false,
[Parameter(Mandatory=$false, ValueFromPipeline=$false, HelpMessage='Grant Site Collection Admin rights to the migration user specified in XML settings file.')]
[Alias("sca")]
[switch]$siteCollectionAdmin = $false
)
# Plugin
Add-PSSnapIn Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue | Out-Null
Import-Module Microsoft.Online.SharePoint.PowerShell -ErrorAction SilentlyContinue -WarningAction SilentlyContinue -Prefix M | Out-Null
Import-Module SharePointPnPPowerShellOnline -ErrorAction SilentlyContinue -WarningAction SilentlyContinue -Prefix P | Out-Null
# Config
$root = Split-Path -Parent -Path $MyInvocation.MyCommand.Definition
[xml]$settings = Get-Content "$root\InsaneMove.xml"
$maxWorker = $settings.settings.maxWorker
Function VerifyPSRemoting() {
"<VerifyPSRemoting>"
$ssp = Get-WSManCredSSP
if ($ssp[0] -match "not configured to allow delegating") {
# Enable remote PowerShell over CredSSP authentication
Enable-WSManCredSSP -DelegateComputer * -Role Client -Force
Restart-Service WinRM
}
}
Function ReadIISPW {
"<ReadIISPW>"
# Read IIS password for current logged in user
Write-Host "===== Read IIS PW ===== $(Get-Date)" -Fore Yellow
# Current user (ex: Farm Account)
$domain = $env:userdomain
$user = $env:username
Write-Host "Logged in as $domain\$user"
# Start IISAdmin if needed
$iisadmin = Get-Service IISADMIN
if ($iisadmin.Status -ne "Running") {
#set Automatic and Start
Set-Service -Name IISADMIN -StartupType Automatic -ErrorAction SilentlyContinue
Start-Service IISADMIN -ErrorAction SilentlyContinue
}
# Attempt to detect password from IIS Pool (if current user is local admin and farm account)
Import-Module WebAdministration -ErrorAction SilentlyContinue | Out-Null
$m = Get-Module WebAdministration
if ($m) {
#PowerShell ver 2.0+ IIS technique
$appPools = Get-ChildItem "IIS:\AppPools\"
foreach ($pool in $appPools) {
if ($pool.processModel.userName -like "*$user") {
Write-Host "Found - "$pool.processModel.userName
$pass = $pool.processModel.password
if ($pass) {
break
}
}
}
} else {
#PowerShell ver 3.0+ WMI technique
$appPools = Get-CimInstance -Namespace "root/MicrosoftIISv2" -ClassName "IIsApplicationPoolSetting" -Property Name, WAMUserName, WAMUserPass | select WAMUserName, WAMUserPass
foreach ($pool in $appPools) {
if ($pool.WAMUserName -like "*$user") {
Write-Host "Found - "$pool.WAMUserName
$pass = $pool.WAMUserPass
if ($pass) {
break
}
}
}
}
# Prompt for password
if (!$pass) {
$sec = Read-Host "Enter password for $domain\$user" -AsSecureString
} else {
$sec = $pass | ConvertTo-SecureString -AsPlainText -Force
}
$global:cred = New-Object System.Management.Automation.PSCredential -ArgumentList "$domain\$user", $sec
}
Function DetectVendor() {
"<DetectVendor>"
# SharePoint Servers in local farm
$spservers = Get-SPServer |? {$_.Role -ne "Invalid"} | sort Address
# Detect if Vendor software installed
$coll = @()
foreach ($s in $spservers) {
$found = Get-ChildItem "\\$($s.Address)\C$\Program Files (x86)\Sharegate\Sharegate.exe" -ErrorAction SilentlyContinue
if ($found) {
$coll += $s.Address
}
}
# Display and return
$coll |% {Write-Host $_ -Fore Green}
$global:servers = $coll
# Safety
if (!$coll) {
Write-Host "No Servers Have ShareGate Installed. Please Verify." -Fore Red
Exit
}
}
Function ReadCloudPW() {
"<ReadCloudPW>"
# Prompt for admin password
$global:cloudPW = Read-Host "Enter O365 Cloud Password for $($settings.settings.tenant.adminUser)"
}
Function CloseSession() {
"<CloseSession>"
# Close remote PS sessions
Get-PSSession | Remove-PSSession
}
Function CreateWorkers() {
"<CreateWorkers>"
# Open worker sessions per server. Runspace to create local SCHTASK on remote PC
# Template command
$cmd = @'
mkdir "d:\InsaneMove" -ErrorAction SilentlyContinue | Out-Null
Function VerifySchtask($name, $file) {
$found = Get-ScheduledTask -TaskName $name -ErrorAction SilentlyContinue
if ($found) {
$found | Unregister-ScheduledTask -Confirm:$false
}
$user = "domain\farm"
$pw = "password"
$folder = Split-Path $file
$a = New-ScheduledTaskAction -Execute "PowerShell.exe" -Argument $file -WorkingDirectory $folder
$p = New-ScheduledTaskPrincipal -RunLevel Highest -UserId $user -LogonType Password
$task = New-ScheduledTask -Action $a -Principal $p
return Register-ScheduledTask -TaskName $name -InputObject $task -Password $pw -User $user
}
VerifySchtask "worker1" "d:\InsaneMove\worker1.ps1"
'@
# Loop available servers
$global:workers = @()
$i = 0
foreach ($pc in $global:servers) {
# Loop maximum worker
$s = New-PSSession -ComputerName $pc -Credential $global:cred -Authentication CredSSP -ErrorAction SilentlyContinue
$s
1..$maxWorker |% {
# create worker
$curr = $cmd -replace "worker1","worker$i"
Write-Host "CREATE Worker$i on $pc ..." -Fore Yellow
$sb = [Scriptblock]::Create($curr)
$result = Invoke-Command -Session $s -ScriptBlock $sb
"[RESULT]"
$result | ft -a
# purge old worker XML output
$resultfile = "\\$pc\d$\insanemove\worker$i.xml"
Remove-Item $resultfile -confirm:$false -ErrorAction SilentlyContinue
# track worker
$obj = New-Object -TypeName PSObject -Prop (@{"Id"=$i;"PC"=$pc})
$global:workers += $obj
$i++
}
}
"WORKERS"
$global:workers | ft -a
}
Function CreateTracker() {
"<CreateTracker>"
# CSV migration source/destination URL
Write-Host "===== Populate Tracking table ===== $(Get-Date)" -Fore Yellow
$i = 0
$j = 0
$global:track = @()
$csv = Import-Csv $fileCSV
foreach ($row in $csv) {
# Assign each row to a Worker
$pc = $global:workers[$j].PC
# Get SharePoint total storage
$site = Get-SPSite $row.SourceURL
if ($site) {
$SPStorage = [Math]::Round($site.Usage.Storage/1MB,2)
}
# MySite URL Lookup
if ($row.MySiteEmail) {
$destUrl = FindCloudMySite $row.MySiteEmail
} else {
$destUrl = $row.DestinationURL;
}
# Add row
$obj = New-Object -TypeName PSObject -Prop (@{
"SourceURL"=$row.SourceURL;
"DestinationURL"=$destUrl;
"MySiteEmail"=$row.MySiteEmail;
"CsvID"=$i;
"WorkerID"=$j;
"PC"=$pc;
"Status"="New";
"SGResult"="";
"SGServer"="";
"SGSessionId"="";
"SGSiteObjectsCopied"="";
"SGItemsCopied"="";
"SGWarnings"="";
"SGErrors"="";
"Error"="";
"ErrorCount"="";
"TaskXML"="";
"SPStorage"=$SPStorage;
"TimeCopyStart"="";
"TimeCopyEnd"=""
})
$global:track += $obj
# Increment ID
$i++
$j++
if ($j -ge $global:workers.count) {
# Reset, back to first Session
$j = 0
}
}
# Display
"[SESSION-CreateTracker]"
Get-PSSession | ft -a
}
Function UpdateTracker () {
"<UpdateTracker>"
# Update tracker with latest SCHTASK status
$active = $global:track |? {$_.Status -eq "InProgress"}
foreach ($row in $active) {
# Monitor remote SCHTASK
$wid = $row.WorkerID
$pc = $row.PC
# Reconnect Broken remote PS
$b = Get-PSSession |? {$_.State -ne "Opened"}
if ($b) {
# Make new session
New-PSSession -ComputerName $b.ComputerName -Credential $global:cred -Authentication CredSSP -ErrorAction SilentlyContinue
# Close old session
$b | Remove-PSSession
}
# Remote session
$s = Get-PSSession |? {$_.ComputerName -eq $pc}
if (!$s) {
# Make new session
New-PSSession -ComputerName $pc -Credential $global:cred -Authentication CredSSP -ErrorAction SilentlyContinue
}
# Check SCHTASK State=Ready
$cmd = "Get-Scheduledtask -TaskName 'worker$wid'"
$sb = [Scriptblock]::Create($cmd)
$schtask = $null
$schtask = Invoke-Command -Session $s -Command $sb
if ($schtask) {
"[SCHTASK]"
$schtask | select {$pc},TaskName,State | ft -a
"[SESSION-UpdateTracker]"
Get-PSSession | ft -a
if ($schtask.State -eq 3) {
$row.Status = "Completed"
$row.TimeCopyEnd = (Get-Date).ToString()
# Do we have ShareGate XML?
$resultfile = "\\$pc\d$\insanemove\worker$wid.xml"
if (Test-Path $resultfile) {
# Read XML
$x = $null
[xml]$x = Get-Content $resultfile
if ($x) {
# Parse XML nodes
$row.SGServer = $pc
$row.SGResult = ($x.Objs.Obj.Props.S |? {$_.N -eq "Result"})."#text"
$row.SGSessionId = ($x.Objs.Obj.Props.S |? {$_.N -eq "SessionId"})."#text"
$row.SGSiteObjectsCopied = ($x.Objs.Obj.Props.I32 |? {$_.N -eq "SiteObjectsCopied"})."#text"
$row.SGItemsCopied = ($x.Objs.Obj.Props.I32 |? {$_.N -eq "ItemsCopied"})."#text"
$row.SGWarnings = ($x.Objs.Obj.Props.I32 |? {$_.N -eq "Warnings"})."#text"
$row.SGErrors = ($x.Objs.Obj.Props.I32 |? {$_.N -eq "Errors"})."#text"
# TaskXML
$row.TaskXML = $x.OuterXml
# Delete XML
Remove-Item $resultfile -confirm:$false -ErrorAction SilentlyContinue
}
# Error
$err = ""
$errcount = 0
$task.Error |% {
$err += ($_|ConvertTo-Xml).OuterXml
$errcount++
}
$row.ErrorCount = $errCount
}
}
}
}
}
Function ExecuteSiteCopy($row, $worker) {
# Parse fields
$name = $row.Name
$srcUrl = $row.SourceURL
# Destination
if ($row.MySiteEmail) {
# MySite /personal/
$destUrl = $row.DestinationURL
} else {
# Team /sites/
$destUrl = FormatCloudMP $row.DestinationURL
}
# Make NEW Session - remote PowerShell
$wid = $worker.Id
$pc = $worker.PC
$s = Get-PSSession |? {$_.ComputerName -eq $pc}
# Generate local secure CloudPW
$sb = [Scriptblock]::Create("""$global:cloudPW"" | ConvertTo-SecureString -Force -AsPlainText | ConvertFrom-SecureString")
$localHash = Invoke-Command $sb -Session $s
# Generate PS1 worker script
$now = (Get-Date).tostring("yyyy-MM-dd_hh-mm-ss")
if ($incremental) {
# Team site INCREMENTAL
$copyparam = "-CopySettings `$csIncr"
}
if ($row.MySiteEmail) {
# MySite /personal/ = always RENAME
$copyparam = "-CopySettings `$csMysite"
}
$ps = "md ""d:\insanemove\log"" -ErrorAction SilentlyContinue;`nStart-Transcript ""d:\insanemove\log\worker$wid-$now.log"";`n""SOURCE=$srcUrl"";`n""DESTINATION=$destUrl"";`n`$secpw=ConvertTo-SecureString -String ""$localHash"";`n`$cred = New-Object System.Management.Automation.PSCredential (""$($settings.settings.tenant.adminUser)"", `$secpw);`nImport-Module ShareGate;`n`$src=`$null;`n`$dest=`$null;`n`$src = Connect-Site ""$srcUrl"";`n`$dest = Connect-Site ""$destUrl"" -Credential `$cred;`n`$csMysite = New-CopySettings -OnSiteObjectExists Merge -OnContentItemExists Rename;`n`$csIncr = New-CopySettings -OnSiteObjectExists Merge -OnContentItemExists IncrementalUpdate;`n`$result = Copy-Site -Site `$src -DestinationSite `$dest -Subsites -Merge $copyparam -InsaneMode -VersionLimit 50;`n`$result | Export-Clixml ""d:\insanemove\worker$wid.xml"" -Force;`nStop-Transcript"
$ps | Out-File "\\$pc\d$\insanemove\worker$wid.ps1" -Force
Write-Host $ps -Fore Yellow
# Invoke SCHTASK
$cmd = "Get-ScheduledTask -TaskName ""worker$wid"" | Start-ScheduledTask"
# Display
Write-Host "START worker $wid on $pc" -Fore Green
Write-Host "$srcUrl,$destUrl" -Fore yellow
# Execute
$sb = [Scriptblock]::Create($cmd)
return Invoke-Command $sb -Session $s
}
Function FindCloudMySite ($MySiteEmail) {
# Lookup /personal/ site URL based on User Principal Name (UPN)
$coll = @()
$coll += $MySiteEmail
$profile = Get-PSPOUserProfileProperty -Account $coll
if ($profile) {
if ($profile.PersonalUrl) {
$url = $profile.PersonalUrl.TrimEnd('/')
}
}
Write-Host "SEARCH for $MySiteEmail found URL $url" -Fore Yellow
return $url
}
Function WriteCSV() {
"<WriteCSV>"
# Write new CSV output with detailed results
$file = $fileCSV.Replace(".csv", "-results.csv")
$global:track | Select SourceURL,DestinationURL,MySiteEmail,CsvID,WorkerID,PC,Status,SGResult,SGServer,SGSessionId,SGSiteObjectsCopied,SGItemsCopied,SGWarnings,SGErrors,Error,ErrorCount,TaskXML,SPStorage | Export-Csv $file -NoTypeInformation -Force -ErrorAction Continue
}
Function CopySites() {
"<CopySites>"
# Monitor and Run loop
Write-Host "===== Start Site Copy to O365 ===== $(Get-Date)" -Fore Yellow
CreateTracker
# Safety
if (!$global:workers) {
Write-Host "No Workers Found" -Fore Red
return
}
$csvCounter = 0
do {
$csvCounter++
# Get latest Job status
UpdateTracker
Write-Host "." -NoNewline
# Ensure all sessions are active
foreach ($worker in $global:workers) {
# Count active sessions per server
$wid = $worker.Id
$active = $global:track |? {$_.Status -eq "InProgress" -and $_.WorkerID -eq $wid}
# Available session. Assign new work
if (!$active) {
# Next row
$row = $global:track |? {$_.Status -eq "New" -and $_.WorkerID -eq $wid}
if ($row) {
if ($row -is [Array]) {
$row = $row[0]
}
# Kick off copy
Start-Sleep 5
"sleep 5 sec..."
$result = ExecuteSiteCopy $row $worker
# Update DB tracking
$row.Status = "InProgress"
$row.TimeCopyStart = (Get-Date).ToString()
}
}
# Progress bar %
$complete = ($global:track |? {$_.Status -eq "Completed"}).Count
$total = $global:track.Count
$prct = [Math]::Round(($complete/$total)*100)
# ETA
if ($prct) {
$elapsed = (Get-Date) - $start
$remain = ($elapsed.TotalSeconds) / ($prct / 100.0)
$eta = (Get-Date).AddSeconds($remain - $elapsed.TotalSeconds)
}
# Display
Write-Progress -Activity "Copy site - ETA $eta" -Status "$name ($prct %)" -PercentComplete $prct
# Detail table
"[TRACK]"
$global:track |? {$_.Status -eq "InProgress"} | select CsvID,WorkerID,PC,SourceURL,DestinationURL | ft -a
$grp = $global:track | group Status
$grp | select Count,Name | sort Name | ft -a
}
# Write CSV with partial results. Enables monitoring long runs.
if ($csvCounter -gt 5) {
WriteCSV
$csvCounter = 0
}
# Latest counter
$remain = $global:track |? {$_.status -ne "Completed" -and $_.status -ne "Failed"}
Start-Sleep 5
"sleep 5 sec..."
} while ($remain)
# Complete
Write-Host "===== Finish Site Copy to O365 ===== $(Get-Date)" -Fore Yellow
"[TRACK]"
$global:track | group status | ft -a
$global:track | select CsvID,JobID,SessionID,SGSessionId,PC,SourceURL,DestinationURL | ft -a
}
Function VerifyCloudSites() {
"<VerifyCloudSites>"
# Read CSV and ensure cloud sites exists for each row
Write-Host "===== Verify Site Collections exist in O365 ===== $(Get-Date)" -Fore Yellow
$global:collMySiteEmail = @()
# Loop CSV
$csv = Import-Csv $fileCSV
foreach ($row in $csv) {
$row | ft -a
EnsureCloudSite $row.SourceURL $row.DestinationURL $row.MySiteEmail
}
# Execute creation of OneDrive /personal/ sites in batches (200 each) https://technet.microsoft.com/en-us/library/dn792367.aspx
Write-Host " - PROCESS MySite bulk creation"
$i = 0
$batch = @()
foreach ($MySiteEmail in $global:collMySiteEmail) {
if ($i -lt 199) {
# append batch
$batch += $MySiteEmail
Write-Host "." -NoNewline
} else {
BulkCreateMysite $batch
$batch = @()
}
}
if ($batch) {
BulkCreateMysite $batch
}
Write-Host "OK"
}
Function BulkCreateMysite ($batch) {
"<BulkCreateMysite>"
# execute and clear batch
Write-Host "`nBATCH Request-SPOPersonalSite $($batch.count)" -Fore Green
$batch
Request-MSPOPersonalSite -UserEmails $batch -NoWait
}
Function EnsureCloudSite($srcUrl, $destUrl, $MySiteEmail) {
"<EnsureCloudSite>"
# Create site in O365 if does not exist
$destUrl = FormatCloudMP $destUrl
Write-Host $destUrl -Fore Yellow
$srcUrl
$web = (Get-SPSite $srcUrl).RootWeb
if ($web.RequestAccessEmail) {
$rae = $web.RequestAccessEmail.Split(",;")[0].Split("@")[0] + "@" + $settings.settings.tenant.suffix;
}
if (!$rae) {
$rae = $settings.settings.tenant.adminUser
}
# Verify SPOUser
try {
$u = Get-SPOUser -Site $settings.settings.tenant.adminURL -LoginName $rae -ErrorAction SilentlyContinue
} catch {}
if (!$u) {
$rae = $settings.settings.tenant.adminUser
}
# Verify SPOSite
try {
$cloud = Get-SPOSite $destUrl -ErrorAction SilentlyContinue
} catch {}
if (!$cloud) {
Write-Host "- CREATING $destUrl"
if ($MySiteEmail) {
# Provision MYSITE
$global:collMySiteEmail += $MySiteEmail
} else {
# Provision TEAMSITE
$quota = 1024*50
New-SPOSite -Owner $rae -Url $destUrl -NoWait -StorageQuota $quota
}
} else {
Write-Host "- FOUND $destUrl"
}
}
Function FormatCloudMP($url) {
# Replace Managed Path with O365 /sites/ only
if (!$url) {return}
$managedPath = "sites"
$i = $url.Indexof("://")+3
$split = $url.SubString($i, $url.length-$i).Split("/")
$split[1] = $managedPath
$final = ($url.SubString(0,$i) + ($split -join "/")).Replace("http:","https:")
return $final
}
Function ConnectCloud {
"<ConnectCloud>"
# Connect SPO
$pw = $global:cloudPW
$pw
$settings.settings.tenant.adminUser
$secpw = ConvertTo-SecureString -String $pw -AsPlainText -Force
$c = New-Object System.Management.Automation.PSCredential ($settings.settings.tenant.adminUser, $secpw)
Connect-PSPOnline -URL $settings.settings.tenant.adminURL -Credential $c
Connect-MSPOService -URL $settings.settings.tenant.adminURL -Credential $c
#$firstUrl = (Get-SPOSite)[0].Url
# Connect PNP
}
Function MeasureSiteCSV {
"<MeasureSiteCSV>"
# Populate CSV with local farm SharePoint site collection size
$csv = Import-Csv $fileCSV
foreach ($row in $csv) {
$s = Get-SPSite $row.SourceURL
if ($s) {
$storage = [Math]::Round($s.Usage.Storage/1GB, 2)
$row.SPStorage = $storage
}
}
$csv | Export-Csv $fileCSV -Force
}
Function LockSite($lock) {
"<LockSite>"
# Modfiy on-prem site collection lock
Write-Host $lock -Fore Yellow
$csv = Import-Csv $fileCSV
foreach ($row in $csv) {
$url = $row.SourceURL
Set-SPSite $url -LockState $lock
"[SPSITE]"
Get-SPSite $url | Select URL,*Lock* | ft -a
}
}
Function SiteCollectionAdmin($user) {
"<SiteCollectionAdmin>"
# Grant site collection admin rights
$csv = Import-Csv $fileCSV
foreach ($row in $csv) {
if ($row.MySiteEmail) {
$url = FindCloudMySite $row.MySiteEmail
} else {
$url = $row.DestinationURL.TrimEnd('/')
}
$url
$site = Get-MSPOSite $url
Set-MSPOUser -Site $site -LoginName $user -IsSiteCollectionAdmin $true
}
}
Function Main() {
"<Main>"
# Start LOG
$start = Get-Date
$when = $start.ToString("yyyy-MM-dd-hh-mm-ss")
$logFile = "$root\log\InsaneMove-$when.txt"
mkdir "$root\log" -ErrorAction SilentlyContinue | Out-Null
if (!$psISE) {Start-Transcript $logFile}
Write-Host "fileCSV = $fileCSV"
# Core logic
if ($measure) {
# Populate CSV with size (GB)
MeasureSiteCSV
} elseif ($readOnly) {
# Lock on-prem sites
LockSite "ReadOnly"
} elseif ($readWrite) {
# Unlock on-prem sites
LockSite "Unlock"
} elseif ($siteCollectionAdmin) {
# Grant cloud sites SCA permission to XML migration cloud user
ReadCloudPW
ConnectCloud
SiteCollectionAdmin $settings.settings.tenant.adminUser
} else {
if ($verifyCloudSites) {
# Create site collection
ReadCloudPW
ConnectCloud
VerifyCloudSites
} else {
# Copy site content
VerifyPSRemoting
ReadIISPW
ReadCloudPW
ConnectCloud
DetectVendor
CloseSession
CreateWorkers
CopySites
CloseSession
WriteCSV
}
}
# Finish LOG
Write-Host "===== DONE ===== $(Get-Date)" -Fore Yellow
$th = [Math]::Round(((Get-Date) - $start).TotalHours, 2)
$attemptMb = ($global:track |measure SPStorage -Sum).Sum
$actualMb = ($global:track |? {$_.SGSessionId -ne ""} |measure SPStorage -Sum).Sum
$actualSites = ($global:track |? {$_.SGSessionId -ne ""}).Count
Write-Host ("Duration Hours : {0:N2}" -f $th) -Fore Yellow
Write-Host ("Total Sites Attempted : {0}" -f $($global:track.count)) -Fore Green
Write-Host ("Total Sites Copied : {0}" -f $actualSites) -Fore Green
Write-Host ("Total Storage Attempted (MB): {0:N0}" -f $attemptMb) -Fore Green
Write-Host ("Total Storage Copied (MB) : {0:N0}" -f $actualMb) -Fore Green
Write-Host ("Total Objects : {0:N0}" -f $(($global:track |measure SGItemsCopied -Sum).Sum)) -Fore Green
Write-Host ("Total Worker Threads : {0}" -f $maxWorker) -Fore Green
Write-Host "=====" -Fore Yellow
Write-Host ("GB per Hour : {0:N2}" -f (($actualMb/1KB)/$th)) -Fore Green
Write-Host $fileCSV
if (!$psISE) {Stop-Transcript}
}
Main