-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSPPatchify.ps1
More file actions
1740 lines (1527 loc) · 60.9 KB
/
SPPatchify.ps1
File metadata and controls
1740 lines (1527 loc) · 60.9 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
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
SharePoint Central Admin - View active services across entire farm. No more select machine drop down dance!
.DESCRIPTION
Apply CU patch to entire farm from one PowerShell console.
NOTE - must run local to a SharePoint server under account with farm admin rights.
Comments and suggestions always welcome! spjeff@spjeff.com or @spjeff
.NOTES
File Namespace : SPPatchify.ps1
Author : Jeff Jones - @spjeff
Version : 0.150
Last Modified : 01-03-2020
.LINK
Source Code
http://www.github.com/spjeff/sppatchify
https://www.spjeff.com/2016/05/16/sppatchify-cu-patch-entire-farm-from-one-script/
Patch Notes
http://sharepointupdates.com
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $False, ValueFromPipeline = $false, HelpMessage = 'Use -d -downloadMediaOnly to execute Media Download only. No farm changes. Prep step for real patching later.')]
[Alias("d")]
[switch]$downloadMediaOnly,
[string]$downloadVersion,
[Parameter(Mandatory = $False, ValueFromPipeline = $false, HelpMessage = 'Use -c -copyMediaOnly to copy \media\ across all peer machines. No farm changes. Prep step for real patching later.')]
[Alias("c")]
[switch]$copyMediaOnly,
[Parameter(Mandatory = $False, ValueFromPipeline = $false, HelpMessage = 'Use -v -showVersion to show farm version info. READ ONLY, NO SYSTEM CHANGES.')]
[Alias("v")]
[switch]$showVersion,
[Parameter(Mandatory = $False, ValueFromPipeline = $false, HelpMessage = 'Use -phaseOneBinary to execute Phase One only (run binary)')]
[switch]$phaseOneBinary,
[Parameter(Mandatory = $False, ValueFromPipeline = $false, HelpMessage = 'Use -quick to run ONLY EXE binary')]
[switch]$quick,
[Parameter(Mandatory = $False, ValueFromPipeline = $false, HelpMessage = 'Use -phaseTwo to execute Phase Two after local reboot.')]
[switch]$phaseTwo,
[Parameter(Mandatory = $False, ValueFromPipeline = $false, HelpMessage = 'Use -phaseThree to execute Phase Three attach and upgrade content.')]
[switch]$phaseThree,
[Parameter(Mandatory = $False, ValueFromPipeline = $false, HelpMessage = 'Use -o -onlineContent to keep content databases online. Avoids Dismount/Mount. NOTE - Will substantially increase patching duration for farms with more user content.')]
[Alias("o")]
[switch]$onlineContent,
[Parameter(Mandatory = $False, ValueFromPipeline = $false, HelpMessage = 'Use -remoteSessionPort to open PSSession (remoting) with custom port number.')]
[string]$remoteSessionPort,
[Parameter(Mandatory = $False, ValueFromPipeline = $false, HelpMessage = 'Use -remoteSessionSSL to open PSSession (remoting) with SSL encryption.')]
[switch]$remoteSessionSSL,
[Parameter(Mandatory = $False, ValueFromPipeline = $false, HelpMessage = 'Use -test to open Remote PS Session and verify connectivity all farm members.')]
[switch]$testRemotePS,
[Parameter(Mandatory = $False, ValueFromPipeline = $false, HelpMessage = 'Use -skipProductLocal to run Phase One binary without Get-SPProduct -Local.')]
[switch]$skipProductLocal = $false,
[Parameter(Mandatory = $False, ValueFromPipeline = $false, HelpMessage = 'Use -targetServers to run for specific machines only. Applicable to PhaseOne and PhaseTwo.')]
[string[]]$targetServers,
[Parameter(Mandatory = $False, ValueFromPipeline = $false, HelpMessage = 'Use -productlocal to execute remote cmdlet [Get-SPProduct -Local] on all servers in farm, or target/wave servers only if given.')]
[switch]$productlocal,
[Parameter(Mandatory = $False, ValueFromPipeline = $false, HelpMessage = 'Use -mount to execute Mount-SPContentDatabase to load CSV and attach content databases to web applications.')]
[string]$mount,
[Parameter(Mandatory = $False, ValueFromPipeline = $false, HelpMessage = 'Use -appOffline TRUE/FALSE to COPY app_offline.htm] file to all servers and all IIS websites (except Default Website).')]
[string]$appOffline,
[Parameter(Mandatory = $False, ValueFromPipeline = $false, HelpMessage = 'Use -bypass to run with PACKAGE.BYPASS.DETECTION.CHECK=1')]
[switch]$bypass,
[Parameter(Mandatory = $False, ValueFromPipeline = $false, HelpMessage = 'Use -changeServices TRUE/FALSE to toggle the farm active state UP/DOWN')]
[string]$changeServices,
[Parameter(Mandatory = $False, ValueFromPipeline = $false, HelpMessage = 'Use -saveServiceInstance to snapshot CSV with current Service Instances running.')]
[switch]$saveServiceInstance
)
# Plugin
Add-PSSnapIn Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue | Out-Null
Import-Module WebAdministration -ErrorAction SilentlyContinue | Out-Null
# Version
if ($phaseTwo) {
$phase = "-phaseTwo"
}
if ($phaseThree) {
$phase = "-phaseThree"
}
$host.ui.RawUI.WindowTitle = "SPPatchify v0.150 $phase"
$rootCmd = $MyInvocation.MyCommand.Definition
$root = Split-Path -Parent -Path $MyInvocation.MyCommand.Definition
$maxattempt = 3
$maxrebootminutes = 120
$logFolder = "$root\log"
#region binary EXE
function MakeRemote($path) {
# Remote UNC
$char = $path.ToCharArray()
if ($char[1] -eq ':') {
$char[1] = '$'
}
return (-join $char)
}
function CopyEXE($action) {
Write-Host "===== $action EXE ===== $(Get-Date)" -Fore "Yellow"
# Clear old session
Get-Job | Remove-Job -Force
Get-PSSession | Remove-PSSession -Confirm:$false
# Start Jobs
foreach ($server in $global:servers) {
$addr = $server.Address
if ($addr -ne $env:computername) {
# Dynamic command
$dest = "\\$addr\$remoteRoot\media"
mkdir $dest -Force -ErrorAction SilentlyContinue | Out-Null;
ROBOCOPY ""$root\media"" ""$dest"" /Z /MIR /W:0 /R:0
}
}
# Watch Jobs
Start-Sleep 5
$counter = 0
do {
foreach ($server in $global:servers) {
# Progress
if (Get-Job) {
$prct = [Math]::Round(($counter / (Get-Job).Count) * 100)
if ($prct) {
Write-Progress -Activity "Copy EXE ($prct %) $(Get-Date)" -Status $addr -PercentComplete $prct -ErrorAction SilentlyContinue
}
}
# Check Job Status
Get-Job | Format-Table -AutoSize
}
Start-Sleep 5
$pending = Get-Job | Where-Object { $_.State -eq "Running" -or $_.State -eq "NotStarted" }
$counter = (Get-Job).Count - $pending.Count
}
while ($pending)
# Complete
Get-Job | Format-Table -a
Write-Progress -Activity "Completed $(Get-Date)" -Completed
}
function SafetyInstallRequired() {
# Display server upgrade
Write-Host "Farm Servers - Upgrade Status " -Fore "Yellow"
(Get-SPProduct).Servers | Select-Object Servername, InstallStatus | Sort-Object Servername | Format-Table -AutoSize
$halt = (Get-SPProduct).Servers | Where-Object { $_.InstallStatus -eq "InstallRequired" }
if ($halt) {
$halt | Format-Table -AutoSize
Write-Host "HALT - MEDIA ERROR - Install on servers" -Fore Red
Exit
}
}
function SafetyEXE() {
Write-Host "===== SafetyEXE ===== $(Get-Date)" -Fore "Yellow"
# Count number of files. Must be 3 for SP2013 (major ver 15)
# Build CMD
$ver = (Get-SPFarm).BuildVersion.Major
if ($ver -eq 15) {
foreach ($server in $global:servers) {
$addr = $server.Address
$c = (Get-ChildItem "\\$addr\$remoteRoot\media").Count
if ($c -ne 3) {
$halt = $true
Write-Host "HALT - MEDIA ERROR - Expected 3 files on \\$addr\$remoteRoot\media" -Fore Red
}
}
# Halt
if ($halt) {
Exit
}
}
}
function RunEXE() {
Write-Host "===== RunEXE ===== $(Get-Date)" -Fore "Yellow"
# Remove MSPLOG
LoopRemoteCmd "Remove MSPLOG on " "Remove-Item '$logfolder\msp\*MSPLOG*' -Confirm:`$false -ErrorAction SilentlyContinue"
# Remove MSPLOG
LoopRemoteCmd "Unblock EXE on " "gci '$root\media\*' | Unblock-File -Confirm:`$false -ErrorAction SilentlyContinue"
# Build CMD
$files = Get-ChildItem "$root\media\*.exe" | Sort-Object Name
foreach ($f in $files) {
# Display patch name
$name = $f.Name
Write-Host $name -Fore Yellow
$patchName = $name.replace(".exe", "")
$cmd = "$root\media\$name"
$params = "/passive /forcerestart /log:""$root\log\msp\$name.log"""
if ($bypass) {
$params += " PACKAGE.BYPASS.DETECTION.CHECK=1"
}
$taskName = "SPPatchify"
# Loop - Run Task Scheduler
foreach ($server in $global:servers) {
# Local PC - No reboot
$addr = $server.Address
if ($addr -eq $env:computername) {
$params = $params.Replace("forcerestart", "norestart")
}
# Remove SCHTASK if found
$found = Get-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue -CimSession $addr
if ($found) {
$found | Unregister-ScheduledTask -Confirm:$false -CimSession $addr
}
# New SCHTASK parameters
$user = "System"
$folder = Split-Path $f
$a = New-ScheduledTaskAction -Execute $cmd -Argument $params -WorkingDirectory $folder -CimSession $addr
$p = New-ScheduledTaskPrincipal -RunLevel Highest -UserId $user -LogonType S4U
# Create SCHTASK
Write-Host "Register and start SCHTASK - $addr - $cmd" -Fore Green
Register-ScheduledTask -TaskName $taskName -Action $a -Principal $p -CimSession $addr
# Event log START
New-EventLog -LogName "Application" -Source "SPPatchify" -ComputerName $addr -ErrorAction SilentlyContinue | Out-Null
Write-EventLog -LogName "Application" -Source "SPPatchify" -EntryType Information -Category 1000 -EventId 1000 -Message "START" -ComputerName $addr
Start-ScheduledTask -TaskName $taskName -CimSession $addr
}
# Watch EXE binary complete
WaitEXE $patchName
}
# SharePoint 2016 Force Reboot
if ($ver -eq 16) {
foreach ($server in $global:servers) {
$addr = $server.Address
if ($addr -ne $env:computername) {
Write-Host "Reboot $($addr)" -Fore Yellow
Restart-Computer -ComputerName $addr
}
}
}
}
function WaitEXE($patchName) {
Write-Host "===== WaitEXE ===== $(Get-Date)" -Fore "Yellow"
# Wait for EXE intialize
Write-Host "Wait 60 sec..."
Start-Sleep 60
# Watch binary complete
$counter = 0
if ($global:servers) {
foreach ($server in $global:servers) {
# Progress
$addr = $server.Address
$prct = [Math]::Round(($counter / $global:servers.Count) * 100)
if ($prct) {
Write-Progress -Activity "Wait EXE ($prct %) $(Get-Date)" -Status $addr -PercentComplete $prct
}
$counter++
# Remote Posh
$attempt = 0
Write-Host "`nEXE monitor started on $addr at $(Get-Date) " -NoNewLine
do {
# Monitor EXE process
$proc = Get-Process -Name $patchName -Computer $addr -ErrorAction SilentlyContinue
Write-Host "." -NoNewLine
Start-Sleep 10
# Priority (High) from https://gallery.technet.microsoft.com/scriptcenter/Set-the-process-priority-9826a55f
$cmd = "`$proc = Get-Process -Name ""$patchName"" -ErrorAction SilentlyContinue; if (`$proc) { if (`$proc.PriorityClass.ToString() -ne ""High"") {`$proc.PriorityClass = [System.Diagnostics.ProcessPriorityClass]::HIGH}}"
$sb = [Scriptblock]::Create($cmd)
Invoke-Command -Session (Get-PSSession) -ScriptBlock $sb
# Measure EXE
$proc | Select-Object Id, HandleCount, WorkingSet, PrivateMemorySize
# Count MSPLOG files
$cmd = "`$f=Get-ChildItem ""$logFolder\*MSPLOG*"";`$c=`$f.count;`$l=(`$f|sort last -desc|select -first 1).LastWriteTime;`$s=`$env:computername;New-Object -TypeName PSObject -Prop (@{""Server""=`$s;""Count""=`$c;""LastWriteTime""=`$l})"
$sb = [Scriptblock]::Create($cmd)
$result = Invoke-Command -Session (Get-PSSession) -ScriptBlock $sb
$progress = "Server: $($result.Server) / MSP Count: $($result.Count) / Last Write: $($result.LastWriteTime)"
Write-Progress $progress
}
while ($proc)
Write-Host $progress
# Check Schtask Exit Code
Start-Sleep 3
$task = Get-ScheduledTask -TaskName $taskName -CimSession $addr
$info = $task | Get-ScheduledTaskInfo
$exit = $info.LastTaskResult
if ($exit -eq 0) {
Write-Host "EXIT CODE $exit - $taskName" -Fore White -Backgroundcolor Green
}
else {
Write-Host "EXIT CODE $exit - $taskName" -Fore White -Backgroundcolor Red
}
# Event Log
New-EventLog -LogName "Application" -Source "SPPatchify" -ComputerName $addr -ErrorAction SilentlyContinue | Out-Null
Write-EventLog -LogName "Application" -Source "SPPatchify" -EntryType Information -Category 1000 -EventId 1000 -Message "DONE - Exit Code $exit" -ComputerName $addr
# Retry Attempt
if ($exit -gt 0) {
# Retry
$attempt++
if ($attempt -lt $maxattempt) {
# Event log START
New-EventLog -LogName "Application" -Source "SPPatchify" -ComputerName $addr -ErrorAction SilentlyContinue | Out-Null
Write-EventLog -LogName "Application" -Source "SPPatchify" -EntryType Information -Category 1000 -EventId 1000 -Message "RETRY ATTEMPT # $attempt" -ComputerName $addr
# Run
Write-Host "RETRY ATTEMPT # $attempt of $maxattempt" -Fore White -Backgroundcolor Red
Start-ScheduledTask -TaskName $taskName -CimSession $addr
}
}
}
}
}
function WaitReboot() {
Write-Host "`n===== WaitReboot ===== $(Get-Date)" -Fore "Yellow"
# Wait for farm peer machines to reboot
Write-Host "Wait 60 sec..."
Start-Sleep 60
# Clean up
Get-PSSession | Remove-PSSession -Confirm:$false
# Verify machines online
$counter = 0
foreach ($server in $global:servers) {
# Progress
$addr = $server.Address
Write-Host $addr -Fore Yellow
if ($addr -ne $env:COMPUTERNAME) {
$prct = [Math]::Round(($counter / $global:servers.Count) * 100)
if ($prct) {
Write-Progress -Activity "Waiting for machine ($prct %) $(Get-Date)" -Status $addr -PercentComplete $prct
}
$counter++
# Remote PowerShell session
do {
# Dynamic open PSSession
if ($remoteSessionPort -and $remoteSessionSSL) {
$remote = New-PSSession -ComputerName $addr -Credential $global:cred -Authentication Credssp -Port $remoteSessionPort -UseSSL
}
elseif ($remoteSessionPort) {
$remote = New-PSSession -ComputerName $addr -Credential $global:cred -Authentication Credssp -Port $remoteSessionPort
}
elseif ($remoteSessionSSL) {
$remote = New-PSSession -ComputerName $addr -Credential $global:cred -Authentication Credssp -UseSSL
}
else {
$remote = New-PSSession -ComputerName $addr -Credential $global:cred -Authentication Credssp
}
# Display
Write-Host "." -NoNewLine
Start-Sleep 5
}
while (!$remote)
}
}
# Clean up
Get-PSSession | Remove-PSSession -Confirm:$false
}
function LocalReboot() {
# Create Regkey
New-Item -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\" -Name "RunOnce" -ErrorAction SilentlyContinue | Out-Null
New-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\RunOnce" -Name "SPPatchify" -Value "PowerShell -executionpolicy unrestricted -file ""$root\SPPatchify.ps1"" -PhaseTwo" -ErrorAction SilentlyContinue | Out-Null
# Reboot
Write-Host "`n ===== REBOOT LOCAL ===== $(Get-Date)"
$th = [Math]::Round(((Get-Date) - $start).TotalHours, 2)
Write-Host "Duration Total Hours: $th" -Fore "Yellow"
Stop-Transcript
Start-Sleep 5
Restart-Computer -Force
Exit
}
function LaunchPhaseThree() {
# Launch script in new windows for Phase Three - Add Content
Start-Process "powershell.exe" -ArgumentList "$root\SPPatchify.ps1 -phaseThree"
}
function CalcDuration() {
Write-Host "===== DONE ===== $(Get-Date)" -Fore "Yellow"
$totalHours = [Math]::Round(((Get-Date) - $start).TotalHours, 2)
Write-Host "Duration Hours: $totalHours" -Fore "Yellow"
$c = (Get-SPContentDatabase).Count
Write-Host "Content Databases Online: $c"
# Add both Phase one and two
$regHive = "HKCU:\Software"
$regKey = "SPPatchify"
if (!$phaseTwo) {
# Create Regkey
New-Item -Path $regHive -Name "$regKey" -ErrorAction SilentlyContinue | Out-Null
New-ItemProperty -Path "$regHive\$regKey" -Name "PhaseOneTotalHours" -Value $totalHours -ErrorAction SilentlyContinue | Out-Null
}
else {
# Read Regkey
$key = Get-ItemProperty -Path "$regHive\PhaseOneTotalHours" -ErrorAction SilentlyContinue
if ($key) {
$totalHours += [double]($key."PhaseOneTotalHours")
}
Write-Host "TOTAL Hours (Phase One and Two): $totalHours" -Fore "Yellow"
Remove-Item -Path "$regHive\$regKey" -ErrorAction SilentlyContinue | Out-Null
}
}
function FinalCleanUp() {
# Close sessions
Get-PSSession | Remove-PSSession -Confirm:$false
Stop-Transcript
}
#endregion
#region SP Config Wizard
function LoopRemotePatch($msg, $cmd, $params) {
if (!$cmd) {
return
}
# Clean up
Get-PSSession | Remove-PSSession -Confirm:$false
# Loop servers
$counter = 0
foreach ($server in $global:servers) {
# Overwrite restart parameter
$ver = (Get-SPFarm).BuildVersion.Major
$addr = $server.Address
if ($ver -eq 16 -or $env:computername -eq $addr) {
$cmd = $cmd.replace("forcerestart", "norestart")
}
# Script block
if ($cmd.GetType().Name -eq "String") {
$sb = [ScriptBlock]::Create($cmd)
}
else {
$sb = $cmd
}
# Progress
$prct = [Math]::Round(($counter / $global:servers.Count) * 100)
if ($prct) {
Write-Progress -Activity $msg -Status "$addr ($prct %) $(Get-Date)" -PercentComplete $prct
}
$counter++
# Remote Posh
Write-Host ">> invoke on $addr" -Fore "Green"
# Dynamic open PSSession
if ($remoteSessionPort -and $remoteSessionSSL) {
$remote = New-PSSession -ComputerName $addr -Credential $global:cred -Authentication Credssp -Port $remoteSessionPort -UseSSL
}
elseif ($remoteSessionPort) {
$remote = New-PSSession -ComputerName $addr -Credential $global:cred -Authentication Credssp -Port $remoteSessionPort
}
elseif ($remoteSessionSSL) {
$remote = New-PSSession -ComputerName $addr -Credential $global:cred -Authentication Credssp -UseSSL
}
else {
$remote = New-PSSession -ComputerName $addr -Credential $global:cred -Authentication Credssp
}
# Invoke
Start-Sleep 3
foreach ($s in $sb) {
Write-Host $s.ToString()
if ($remote) {
Invoke-Command -Session $remote -ScriptBlock $s
}
}
Write-Host "<< complete on $addr" -Fore "Green"
}
Write-Progress -Activity "Completed $(Get-Date)" -Completed
}
function LoopRemoteCmd($msg, $cmd) {
if (!$cmd) {
return
}
# Clean up
Get-PSSession | Remove-PSSession -Confirm:$false
# Loop servers
$counter = 0
foreach ($server in $global:servers) {
Write-Host $server.Address -Fore Yellow
# Script block
if ($cmd.GetType().Name -eq "String") {
$sb = [ScriptBlock]::Create($cmd)
}
else {
$sb = $cmd
}
# Progress
$addr = $server.Address
$prct = [Math]::Round(($counter / $global:servers.Count) * 100)
if ($prct) {
Write-Progress -Activity $msg -Status "$addr ($prct %) $(Get-Date)" -PercentComplete $prct
}
$counter++
# Remote Posh
Write-Host ">> invoke on $addr" -Fore "Green"
# Dynamic open PSSesion
if ($remoteSessionPort -and $remoteSessionSSL) {
$remote = New-PSSession -ComputerName $addr -Credential $global:cred -Authentication Credssp -Port $remoteSessionPort -UseSSL
}
elseif ($remoteSessionPort) {
$remote = New-PSSession -ComputerName $addr -Credential $global:cred -Authentication Credssp -Port $remoteSessionPort
}
elseif ($remoteSessionSSL) {
$remote = New-PSSession -ComputerName $addr -Credential $global:cred -Authentication Credssp -UseSSL
}
else {
$remote = New-PSSession -ComputerName $addr -Credential $global:cred -Authentication Credssp
}
# Merge script block array
$mergeSb = $sb
$mergeCmd = ""
if ($sb -is [array]) {
foreach ($s in $sb) {
$mergeCmd += $s.ToString() + "`n"
}
$mergeSb = [Scriptblock]::Create($mergeCmd)
}
# Invoke
Start-Sleep 3
if ($remote) {
Write-Host $mergeSb.ToString()
Invoke-Command -Session $remote -ScriptBlock $mergeSb
}
Write-Host "<< complete on $addr" -Fore "Green"
}
Write-Progress -Activity "Completed $(Get-Date)" -Completed
}
function ChangeDC() {
Write-Host "===== ChangeDC OFF ===== $(Get-Date)" -Fore "Yellow"
# Distributed Cache
$sb = {
try {
Use-CacheCluster
Get-AFCacheClusterHealth -ErrorAction SilentlyContinue
$computer = [System.Net.Dns]::GetHostByName($env:computername).HostName
$counter = 0
$maxLoops = 60
$cache = Get-CacheHost | Where-Object { $_.HostName -eq $computer }
if ($cache) {
do {
try {
# Wait for graceful stop
$hostInfo = Stop-CacheHost -Graceful -CachePort 22233 -HostName $computer -ErrorAction SilentlyContinue
Write-Host $computer $hostInfo.Status
Start-Sleep 5
$counter++
}
catch {
break
}
}
while ($hostInfo -and $hostInfo.Status -ne "Down" -and $counter -lt $maxLoops)
# Force stop
Add-PSSnapIn Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue | Out-Null
Stop-SPDistributedCacheServiceInstance
}
}
catch {
}
}
LoopRemoteCmd "Stop Distributed Cache on " $sb
}
function ChangeServices($state) {
Write-Host "===== ChangeServices $state ===== $(Get-Date)" -Fore "Yellow"
$ver = (Get-SPFarm).BuildVersion.Major
# Logic core
if ($state) {
$action = "START"
$sb = {
@("IISADMIN", "W3SVC", "SPAdminV4", "SPTimerV4", "SQLBrowser", "Schedule", "SPInsights", "DocAve 6 Agent Service") | ForEach-Object {
if (Get-Service $_ -ErrorAction SilentlyContinue) {
Set-Service -Name $_ -StartupType Automatic -ErrorAction SilentlyContinue
Start-Service $_ -ErrorAction SilentlyContinue
}
}
@("OSearch$ver", "SPSearchHostController") | ForEach-Object {
Start-Service $_ -ErrorAction SilentlyContinue
}
Start-Process 'iisreset.exe' -ArgumentList '/start' -Wait -PassThru -NoNewWindow | Out-Null
}
}
else {
$action = "STOP"
$sb = {
Start-Process 'iisreset.exe' -ArgumentList '/stop' -Wait -PassThru -NoNewWindow | Out-Null
@("IISADMIN", "W3SVC", "SPAdminV4", "SPTimerV4", "SQLBrowser", "Schedule", "SPInsights", "DocAve 6 Agent Service") | ForEach-Object {
if (Get-Service $_ -ErrorAction SilentlyContinue) {
Set-Service -Name $_ -StartupType Disabled -ErrorAction SilentlyContinue
Stop-Service $_ -ErrorAction SilentlyContinue
}
}
@("OSearch$ver", "SPSearchHostController") | ForEach-Object {
Stop-Service $_ -ErrorAction SilentlyContinue
}
}
}
# Search Crawler
Write-Host "$action search crawler ..."
try {
$ssa = Get-SPEenterpriseSearchServiceApplication
if ($state) {
$ssa.resume()
}
else {
$ssa.pause()
}
}
catch {
}
LoopRemoteCmd "$action services on " $sb
}
function RunConfigWizard() {
Write-Host "===== RunConfigWizard =====" -Fore Yellow
# Shared
$shared = {
Add-PSSnapIn Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue | Out-Null
$ver = (Get-SPFarm).BuildVersion.Major
$psconfig = "C:\Program Files\Common Files\microsoft shared\Web Server Extensions\$ver\BIN\psconfig.exe"
}
# Save B2B shortcut
$b2b = {
$file = $psconfig.replace("psconfig.exe", "psconfigb2b.cmd")
if (!(Test-Path $file)) {
"psconfig.exe -cmd upgrade -inplace b2b -force" | Out-File $file -Force
}
}
LoopRemoteCmd "Save B2B shortcut on " @($shared, $b2b)
# Run Config Wizard - https://blogs.technet.microsoft.com/stefan_gossner/2015/08/20/why-i-prefer-psconfigui-exe-over-psconfig-exe/
$wiz = {
& "$psconfig" -cmd "upgrade" -inplace "b2b" -wait -cmd "applicationcontent" -install -cmd "installfeatures" -cmd "secureresources" -cmd "services" -install
}
LoopRemoteCmd "Run Config Wizard on " @($shared, $wiz)
}
function ChangeContent($state) {
Write-Host "===== ContentDB $state ===== $(Get-Date)" -Fore "Yellow"
# Display
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint") | Out-Null
$c = (Get-SPContentDatabase).Count
Write-Host "Content Databases Online: $c"
if (!$state) {
# Remove content
$dbs = Get-SPContentDatabase
if ($dbs) {
$dbs | ForEach-Object { $wa = $_.WebApplication.Url; $_ | Select-Object Name, NormalizedDataSource, @{n = "WebApp"; e = { $wa } } } | Export-Csv "$logFolder\contentdbs-$when.csv" -NoTypeInformation
$dbs | ForEach-Object {
"$($_.Name),$($_.NormalizedDataSource)"
Dismount-SPContentDatabase $_ -Confirm:$false
}
}
}
else {
# Add content
$files = Get-ChildItem "$logFolder\contentdbs-*.csv" | Sort-Object LastAccessTime -Desc
if ($files -is [Array]) {
$files = $files[0]
}
# Loop databases
if ($files) {
Write-Host "Content DB - Mount from CSV $($files.Fullname)" -Fore Yellow
$dbs = @()
$dbs += Import-Csv $files.Fullname
$counter = 0
if ($dbs) {
$dbs | Where-Object {
$name = $_.Name
$name
# Progress
$prct = [Math]::Round(($counter / $dbs.Count) * 100)
if ($prct) {
Write-Progress -Activity "Add database" -Status "$name ($prct %) $(Get-Date)" -PercentComplete $prct
}
$counter++
$wa = [Microsoft.SharePoint.Administration.SPWebApplication]::Lookup($_.WebApp)
if ($wa) {
Mount-SPContentDatabase -WebApplication $wa -Name $name -DatabaseServer $_.NormalizedDataSource | Out-Null
}
}
}
}
else {
Write-Host "Content DB - CSV not found" -Fore Yellow
}
}
}
#endregion
#region general
function EnablePSRemoting() {
$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 {
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 IISAdm` 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-Object 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 " -AsSecureString
}
else {
$sec = $pass | ConvertTo-SecureString -AsPlainText -Force
}
# Save global
$global:cred = New-Object System.Management.Automation.PSCredential -ArgumentList "$domain\$user", $sec
}
function DisplayCA() {
# Version DLL File
$sb = {
Add-PSSnapIn Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue | Out-Null;
$ver = (Get-SPFarm).BuildVersion.Major;
[System.Diagnostics.FileVersionInfo]::GetVersionInfo("C:\Program Files\Common Files\microsoft shared\Web Server Extensions\$ver\ISAPI\Microsoft.SharePoint.dll") | Select-Object FileVersion, @{N = 'PC'; E = { $env:computername } }
}
LoopRemoteCmd "Get file version on " $sb
# Display Version
ShowVersion
# Open Central Admin
$ca = (Get-SPWebApplication -IncludeCentralAdministration) | Where-Object { $_.IsAdministrationWebApplication -eq $true }
$pages = @("PatchStatus.aspx", "UpgradeStatus.aspx", "FarmServers.aspx")
$pages | ForEach-Object { Start-Process ($ca.Url + "_admin/" + $_) }
}
function ShowVersion() {
# Version Max Patch
$maxv = 0
$f = Get-SPFarm
$p = Get-SPProduct
foreach ($u in $p.PatchableUnitDisplayNames) {
$n = $u
$v = ($p.GetPatchableUnitInfoByDisplayName($n).patches | Sort-Object version -desc)[0].version
if (!$maxv) {
$maxv = $v
}
if ($v -gt $maxv) {
$maxv = $v
}
}
# Control Panel Add/Remove Programs
# IIS UP/DOWN Load Balancer
Write-Host "IIS UP/DOWN Load Balancer"
$coll = @()
$global:servers | ForEach-Object {
try {
$addr = $_.Address;
$root = (Get-Website "Default Web Site").PhysicalPath.ToLower().Replace("%systemdrive%", $env:SystemDrive)
$remoteRoot = "\\$addr\"
$remoteRoot += MakeRemote $root
$status = (Get-Content "$remoteRoot\status.html" -ErrorAction SilentlyContinue)[1];
$coll += @{"Server" = $addr; "Status" = $status }
}
catch {
# Suppress any error
}
}
$coll | Format-Table -AutoSize
# Database table
$d = Get-SPWebapplication -IncludeCentralAdministration | Get-SPContentDatabase
$d | Sort-Object NeedsUpgrade, Name | Select-Object NeedsUpgrade, Name | Format-Table -AutoSize
# Database summary
$d | Group-Object NeedsUpgrade | Format-Table -AutoSize
"---"
# Server status table
(Get-SPProduct).Servers | Select-Object Servername, InstallStatus -Unique | Group-Object InstallStatus, Servername | Sort-Object Name | Format-Table -AutoSize
# Server status summary
(Get-SPProduct).Servers | Select-Object Servername, InstallStatus -Unique | Group-Object InstallStatus | Sort-Object Name | Format-Table -AutoSize
# Display data
if ($maxv -eq $f.BuildVersion) {
Write-Host "Max Product = $maxv" -Fore Green
Write-Host "Farm Build = $($f.BuildVersion)" -Fore Green
}
else {
Write-Host "Max Product = $maxv" -Fore Yellow
Write-Host "Farm Build = $($f.BuildVersion)" -Fore Yellow
}
}
function IISStart() {
# Start IIS pools and sites
$sb = {
Import-Module WebAdministration
# IISAdmin
$iisadmin = Get-Service "IISADMIN"
if ($iisadmin) {
Set-Service -Name $iisadmin -StartupType Automatic -ErrorAction SilentlyContinue
Start-Service $iisadmin -ErrorAction SilentlyContinue
}
# W3WP
Start-Service w3svc | Out-Null
Get-ChildItem "IIS:\AppPools\" | ForEach-Object { $n = $_.Name; Start-WebAppPool $n | Out-Null }
Get-WebSite | Start-WebSite | Out-Null
}
LoopRemoteCmd "Start IIS on " $sb
}
function ProductLocal() {
# Sync local SKU binary to config DB
$sb = {
Add-PSSnapIn Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue | Out-Null
Get-SPProduct -Local
}
LoopRemoteCmd "Product local SKU on " $sb
# Display server upgrade
Write-Host "Farm Servers - Upgrade Status " -Fore "Yellow"
(Get-SPProduct).Servers | Select-Object Servername, InstallStatus | Sort-Object Servername | Format-Table -AutoSize
}
function UpgradeContent() {
Write-Host "===== Upgrade Content Databases ===== $(Get-Date)" -Fore "Yellow"
# Tracking table - assign DB to server
$maxWorkers = 4
$track = @()
$dbs = Get-SPContentDatabase
$i = 0
foreach ($db in $dbs) {
# Assign to SPServer
$mod = $i % $global:servers.count
$pc = $global:servers[$mod].Address
# Collect
$obj = New-Object -TypeName PSObject -Prop (@{"Name" = $db.Name; "Id" = $db.Id; "UpgradePC" = $pc; "JID" = 0; "Status" = "New" })
$track += $obj
$i++
}
$track | Format-Table -Auto
# Clean up
Get-PSSession | Remove-PSSession -Confirm:$false
Get-Job | Remove-Job
# Open sessions
foreach ($server in $global:servers) {
$addr = $server.Address
# Dynamic open PSSesion
if ($remoteSessionPort -and $remoteSessionSSL) {
New-PSSession -ComputerName $addr -Credential $global:cred -Authentication Credssp -Port $remoteSessionPort -UseSSL | Out-Null
}
elseif ($remoteSessionPort) {
New-PSSession -ComputerName $addr -Credential $global:cred -Authentication Credssp -Port $remoteSessionPort | Out-Null
}
elseif ($remoteSessionSSL) {
New-PSSession -ComputerName $addr -Credential $global:cred -Authentication Credssp -UseSSL | Out-Null
}
else {
New-PSSession -ComputerName $addr -Credential $global:cred -Authentication Credssp | Out-Null
}
}
# Monitor and Run loop
do {
# Get latest PID status
$active = @($track | Where-Object { $_.Status -eq "InProgress" })
foreach ($db in $active) {
# Monitor remote server job
if ($db.JID) {
$job = Get-Job $db.JID
if ($job.State -eq "Completed") {
# Update DB tracking
$db.Status = "Completed"
}
elseif ($job.State -eq "Failed") {
# Update DB tracking
$db.Status = "Failed"
}
else {
Write-host "-" -NoNewline
}
}
}