-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSharePointTasks.ps1
More file actions
1824 lines (1493 loc) · 65.3 KB
/
Copy pathSharePointTasks.ps1
File metadata and controls
1824 lines (1493 loc) · 65.3 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
Performs multiple tasks for the SharePoint Farm via a menu.
.DESCRIPTION
Changes account passwords using the provided CSV (inputfile), restarts the farm and other tasks.
.EXAMPLE
.\SharePoint2016Tasks.ps1
.NOTES
Author: Lee Dickey
Date: 26 June 2019
Version: 3.1
V3.2 04/16/2023
- Added proper Parameter use for the most common configuration variables
- To do: Possible refactor to pnpPowershell?
V 3.1 06/26/2019
- Fixed a bug with one function not working due to a -WhatIf left behind after development (whoops!)
- Minor text fixes for easier log reading
- Fixed bug with the log not getting created and encrypted on first run of the script
V 3.0 06/24/2019 -COMPLETE REWRITE-
- Added logging function to both capture a log and display to the host (LoggerLee)
- Log file is created at first run of the script and is immediately encrypted
- Rewrote all of the functions requiring the invoke-command to properly make future troubleshooting easier
- Most all of the functions now use a template (for the most part) that makes modification easier if required
- Corrected error handling actions (stop instead of continue)
- Rewrote Job handling so it makes more sense
- Added a function to change passswords on existing Scheduled Tasks (needs additional testing)
- Fixed a number of bugs that cropped up over the past year.
UNTESTED:
- Added encrypting and decrypting of the $logfile to the menu and actions, HOWEVER, the log file changes from run-to-run. Would be best
to delete the log files once completed to prevent leakage of credential data.
V 2.2 05/07/2018
- Added commands to encrypt and decrypt the Accounts.csv file.
* Only the user that encrypted the file can read and decrypt it.
- Add new commands to list the App Pools and Windows services that will be affected by the scripts other commands
- Added more details to the .Requirements for firewall permissions, WinRM activation, and PowerShell features
- Removed outdated and no longer used functions
V 2.1 06/13/2017
- Added new function to restart running Windows Services specific to SharePoint
- Added new function to recycle AppPools specific to the SharePoint farm
- Added secondary sub-menu for post-password change troubleshooting tasks (some are dupes)
- Cleaned up font coloring and text formatting
V 2.0 05/24/2017
- Enabled parrallel processing of tasks to multiple functions to speed up tasks using PowerShell jobs.
- Minor text fixes
V 1.2 04/25/2017
- Completely rewrote the menu system which improves functionality in a significant way and shortens the code to 1/3 original length.
- Minor text and formatting fixes
V 1.1 04/20/2017
- Corrected output formatting issues with function to start App Pools
- Removed a clear-host and pause command from the function to Unlock Site collections
- Other minor fixes to output formatting to clean up readability
Known Issues
FIXED - Logging - is not working correctly. Disabled for now
V 1.0:
- First Official version. Has functions that are to be used primarily in a SharePoint environment that
do not allow SharePoint to work as intended when using SP Managed Accounts to manage service account password changes.
- To do:
- Move editable variables / values to the top of the script
DONE - Add checks for locked out accounts to AD password changes
DONE - Add checks for locked out accounts to SP Managed Account Password changes
DONE - Other things I haven't thought of yet.
- Some features include:
- Fully menu driven. Just run the script as an administrator
- Check against list of accounts to confirm if the AD accounts are locked and will attempt to unlock them for you
- (SharePoint) Lock and Unlock Site collections (Must be configured to match your environment. Sorry about it not being easier)
- (SharePoint) Start and Stop all SharePoint Timer Services on each SharePoint server
- Check against list of credentials to determine if App Pools using those credentials are running and will try to start them.
- Check against list of credentials to determine if Windows Services using those credentials are running and will try to start them
- Will change passwords in Active Directory if required csv file is provided (See Parameters)
- Will change passwords for App Pools and Windows Services on each server using required csv file (See Parameters)
- (SharePoint) Will display list of SharePoint farm servers and their roles (may need to be configured depending on environment)
.REQUIREMENTS
- Powershell 3.0 or higher
- WinRM must be enabled and remote Powershell must also be enabled
- Check if WinRM is running by using this PowerShell command as admin: get-service winrm
- If not running, run the following PowerShell command as admin: Enable-PSRemoting –force
- Check firewall and make sure the following firewall rules are open on the server using the 'Windows Firewall with Advanced Security'
* Windows Remote Management - Compatibility Mode (HttP-IncludePortInSPN)
* Window Remote Management (HTPP-In)
- The following commands may need to be run on all of the servers running IIS if using 2008 R2 server
* Import-Module ServerManager
* Add-WindowsFeature Web-Scripting-Tools
- Run this PowerShell one-time only on the server running this script: Add-WindowsFeature RSAT-AD-PowerShell
- Service Principle Names (SPNs) may be required for your systems depending on the environment
- Special SPNs were required for the Powershell port (5985 and 5986 (SSL))
Example: setspn -s HTTP/Server-Short-Name-001:5985 Server-Account-Name-01
setspn -s HTTP/Server-Long-Name-001-Is-Very-Long-:5985 Server-Account-Name-01
setspn -s HTTPS/Server-Short-Name-001:5986 Server-Account-Name-01
setspn -s HTTPS/Server-Long-Name-001-Is-Very-Long-:5986 Server-Account-Name-01
#>
######################################
### Parameters ###
######################################
[cmdletbinding()]
param (
# The default input file containing the accounts and passwords
[string] $Global:InputFile = "c:\Scripts\accounts.csv",
[string]$logfile = "c:\SharePointTaskLog_" + (Get-Date -UFormat %Y-%m-%d) + ".log",
# Set the TimeOut limit in seconds for the background jobs. 60-120 seconds does not seem to be long enough in some environments
[string] $JobTimeout = '300'
)
##################################################
### Check for Admin Privileges ###
##################################################
If (-NOT ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole(`
[Security.Principal.WindowsBuiltInRole] "Administrator"))
{
Write-Warning "You do not have Administrator rights to run this script!`nPlease re-run this script as an Administrator!`n(Right-Click Powershell Icon, Click 'Run as Administrator')"
Break
} ###############################################
### Add Snappin
Add-PSSnapin Microsoft.Sharepoint.Powershell
#####################################
### Logging and Output Function ###
#####################################
<#
Requirements: Log file path set for variable $logfile
Usage: Generates output for both the console and for a log file
Example: LoggerLee -Text "error message or $ErrorMsg" -Logtype "error"
Author(s): Lee Dickey #>
function LoggerLee() {
[CmdletBinding()]
param (
[parameter(Mandatory=$True)] [String]$text,
[ValidateSet("low","info","warning","error","success")][string]$logType = "info",
[ValidateSet("newline","nonewline")][string]$linebreak = "newline"
)
Switch ($logType)
{
"warning" {
$color = "yellow";
$bgcolor = "black";
}
"error" {
$color = "red";
$bgcolor = "black";
}
"info" {
$color = "white";
$bgcolor = "blue";
}
"success" {
$color = "Green";
$bgcolor = "DarkBlue";
}
"low" {
$color = "DarkGray";
$bgcolor = "Darkblue";
}
}
Switch ($linebreak)
{
"nonewline" {
$nobreak = "-NoNewLine";
}
"newline" {
$nobreak = "";
}
}
$LogTime = get-date -Format g
if ($logtype -eq "low")
{ write-host "$Text" -ForegroundColor $color -nonewline
if ($linebreak -eq "newline") {write-host ""} }
else
{ Write-Output "`n >> $LogTime - $Text" | out-file $logfile -Append;
write-host "$Text" -ForegroundColor $color -BackgroundColor $bgcolor -nonewline
if ($linebreak -eq "newline") {write-host ""} }
}
LoggerLee -text "Logfile Created $logtime`n" -LogType Info -linebreak newline
Cipher /E $logfile | out-null
##################################################################
# Getting the SharePoint servers the SharePoint way!
##################################################################
# NOTE: This is for EPM2016 environment.
# Other SharePoint farms may have other server roles!
##################################################################
function GetSharePointServers
{
# Get Search Servers
$Global:SearchServers = (Get-SPServer | Where-Object {($_.Role -eq "Search")} | Select-Object @{Name = "ServerName"; Expression = {$_.Address}} | ConvertTo-CSV -NoTypeInformation | Select-Object -skip 1 | % {$_ -replace '"',''}) | Out-String
# Get SSRS Server
$Global:SSRSservers = (Get-SPServer | Where-Object {($_.Role -eq "custom")} | Select-Object @{Name = "ServerName"; Expression = {$_.Address}} | ConvertTo-CSV -NoTypeInformation | Select-Object -skip 1 | % {$_ -replace '"',''}) | Out-String
# Get Application servers
$Global:APPServers = (Get-SPServer | Where-Object {($_.Role -eq "Application")} | Select-Object @{Name = "ServerName"; Expression = {$_.Address}} | ConvertTo-CSV -NoTypeInformation | Select-Object -skip 1 | % {$_ -replace '"',''}) | Out-String
# Get Cache servers
$Global:CacheServers = (Get-SPServer | Where-Object {($_.Role -eq "DistributedCache")} | Select-Object @{Name = "ServerName"; Expression = {$_.Address}} | ConvertTo-CSV -NoTypeInformation | Select-Object -skip 1 | % {$_ -replace '"',''}) | Out-String
# Get Web Servers
$Global:WebServers = (Get-SPServer | Where-Object {($_.Role -eq "WebFrontEnd")} | Select-Object @{Name = "ServerName"; Expression = {$_.Address}} | ConvertTo-CSV -NoTypeInformation | Select-Object -skip 1 | % {$_ -replace '"',''}) | Out-String
# Get Database Server
$db = (Get-SPDatabase)[0]
$Global:DBServers = $db.Server.Address
# Full list of SharePoint Servers in the farm (except DB)
$Global:Servers = Get-SPServer | Where-Object {$_.Role -ne "Invalid"} | select DisplayName
$Global:SPServers = $Servers.DisplayName
}
GetSharePointServers
######################################################
### Acquires required accounts for SharePoint farm ###
######################################################
function Get-Accounts
{
LoggerLee "`n`nBuilding list of AD accounts...`n`n" info
if($Global:accounts)
{$Global:accounts = $null}
Start-Sleep 5
$Global:accounts = (Import-Csv $InputFile | Where {(($_ -notmatch "mssql") -and ($_ -notmatch "agent") -and ($_ -notmatch "ssas") )} | ConvertTo-CSV -NoTypeInformation | % {$_ -replace '"',''}) | Out-String
}
#######################################################
# PowerShell Jobs - Wait to be completed
#######################################################
# Waits for the PowerShell job on the server to reach the required state.
function WaitForJob([string]$jobName, [string]$jobState)
{
LoggerLee -text "`n`nWaiting for a background job to be $jobState" low nonewline
do
{
Start-Sleep 1
Write-Host -foregroundcolor DarkGray -NoNewline "."
$jobstatus = get-job -name $jobName
}
while ($jobstatus.State -ne $jobState)
Write-Host " "
Write-Host " "
#Write-Host -foregroundcolor DarkGray -NoNewLine " The job $jobName is "
#Write-Host -foregroundcolor Gray $jobState
#LoggerLee " The background job is " low nonewline
#LoggerLee "$jobState`n" low
}
######################################################################
# Check to verify that remote access is possible via Invoke-Command
######################################################################
function WinRMVerify
{
remove-job *
LoggerLee "`n`nVerifying the script can access each of the servers to perform remote actions....`n`n" info
###*****************************************************************************************###
### Checks all of the servers to ensure the invoke-command will work. Most everything else
### will not work if this check fails.
###*****************************************************************************************###
foreach ($system in $SPServers)
{
$SessionOption = New-PSSessionOption -IncludePortInSPN
Try
{
Invoke-Command -ComputerName $system -SessionOption $SessionOption -ErrorAction Stop -ScriptBlock {
$result = [PSCustomObject]@{
Success = $false
Message = $null
Completed = $false
Serv = $using:system
}
Try
{
$result.message = "Remote Access successful on $Using:system`n"
Write-Output $result.message -ErrorAction stop
$result.success = $true
}
Catch
{
$result.message = $_.Exception.Message;
$result.success = $false
}
$result
} -AsJob | Out-Null
}
Catch {
LoggerLee "Could not invoke a remote connection to $server`n" warning;
LoggerLee "$_.Exception.Message" error;
exit
}
}
#Start of Jobs retrieval
$jobs = get-job # | wait-job -timeout 120
foreach ($job in $jobs){
WaitForJob $job.name "Completed"
$jobresult = $job | receive-job
if ($jobresult.success -eq $true)
{
LoggerLee -text "$($jobresult.message)" success
}
else
{
LoggerLee "This was a failure on $($jobresult.serv)" warning;
LoggerLee "$($jobresult.message)`n`n" error
} }
# Clears or resets variables
$accounts = $null
remove-job *
}
#########################################################
# (SharePoint) Locking the Site Collections
#########################################################
function LockSPSites
{
# Collects list of Site Collections that are primarily used while avoiding mysites and other junk
# Will need to be modified to match different SharePoint environments
$SiteCollection = Get-SPSite | Where-Object {($_.Url -match "epm16") -or ($_.Url -match "epm16-my") -and ($_.Url -notmatch "personal") } | select Url
$SiteCollections = $SiteCollection.Url
LoggerLee -Text "`n`nLocking the site collections...." Warning
Start-Sleep -s 5
foreach ($sc in $SiteCollections)
{
#Locks the site collections to prevent corruption to the database
#if someone tries to make changes while everything is going on
Try
{
Set-SPSite -Identity $sc -LockState "ReadOnly" -ErrorAction Stop;
LoggerLee -Text "Locked the site collection: $sc" -LogType Success
}
Catch
{
LoggerLee -Text "Cannot lock site collection: $sc" Error;
LoggerLee -Text "Please check the logs for details." Error;
LoggerLee $_.Exception.Message Error
}
}
#Pause
}
###########################################################
# (SharePoint) Unlocking the site Collections
###########################################################
function UnlockSPSites
{
#Collects list of Site Collections that are primarily used while avoiding mysites and other junk
$SiteCollection = Get-SPSite | Where-Object {($_.Url -match "epm16") -or ($_.Url -match "epm16-my") -and ($_.Url -notmatch "personal") } | select Url
$SiteCollections = $SiteCollection.Url
LoggerLee "`n`nUnlocking Site Collections....`n" Warning
foreach ($sc in $SiteCollections)
{
# Unlocks the site collections that are typically used for typical use
Try
{
Set-SPSite -Identity $sc -LockState "Unlock" -ErrorAction Stop;
LoggerLee "Unlocked the site collection: $sc" Success
}
Catch
{ LoggerLee "Cannot Unlock site collection: $sc" Error;
LoggerLee "Please check the logs for details" Error;
LoggerLee $_.Exception.Message Error
}
}
LoggerLee "`nTask Completed.`n`n" Info
#Pause
#cls
}
###########################################################
# Restart all of the servers (not DB)
###########################################################
function RestartFarm
{
#Start-Transcript -Path $Logfile -IncludeInvocationHeader -Append -Force
LoggerLee "`n`n`nSharePoint Servers (Not SQL) to be restarted!" Info
LoggerLee "Type 'Yes' and press enter to restart all SharePoint servers (not DB server)!" Warning
$RestartSPServers = Read-Host 'Yes or No (Default Yes) >>'
if (($RestartSPServers -eq 'Yes') -or ($RestartSPServers -eq "y"))
{
# Rebuilds the server list excluding the current logged in system to avoid rebooting the system you are currently using
$SPServers = $SPServers | Where-Object {$_ -ne $env:computername}
foreach ($server in $SPServers) {
Try
{
LoggerLee "Restarting $server..." Info;
restart-computer -computername $server -ErrorAction stop ;
LoggerLee "$server successfully restarted" success
Start-Sleep -s 2
}
Catch
{
LoggerLee "Unable to restart $server. Investigate and restart manually asap!" Error;
$restarterror1 = "$_.Exception.Message";
LoggerLee -text $restarterror1 -LogType Error;
Pause
}
}
LoggerLee "`n`nAll other servers have been restarted. This server (you are on) must now be restarted." Warning;
LoggerLee "`nSave all work and press ENTER to reboot this system." Info;
pause;
LoggerLee "`nAfter this system reboots, give all processes and services 5 to 10 minutes to start up before you continue." warning;
Start-Sleep -s 30;
Try
{
LoggerLee "`nRestarting system $env:computername...`n" Info
restart-computer -computername "$env:computername" -ErrorAction Stop;
LoggerLee "$env:computername successfully restarted`n" Success
}
Catch
{
LoggerLee "Unable to reboot this server $server. Manually restart when ready" error;
$restarterror2 = "$_.Exception.Message";
LoggerLee $restarterror2 error
}
Finally
{
LoggerLee "Please manually restart any servers that did not restart then continue!" info;
Pause
}
}
else
{LoggerLee "`n`nExited without restarting the SharePoint App and Web servers. This may be required at a later time." warning}
#Stop-Transcript
}
#####################################
# Prompt to restart SQL Server
#####################################
function RestartSQL
{
cls
LoggerLee "Type Yes to restart the database server $DBServers" warning
LoggerLee "`nType 'Yes' or press enter in order to restart the server" info
$RestartDB = Read-Host ' Restart SQL Servers? Yes or No. (Default No) '
if (($RestartDB -eq 'Yes') -or ($RestartDB -eq 'y'))
{
Try {
LoggerLee "`n`nRestarting the database server $DBServers....`n" info
Restart-Computer -ComputerName $DBServers -Force -ErrorAction Stop;
#While (Test-Connection -Quiet -Delay 1 $DBServers) {Write-Host "Waiting for $DBServers to restart and go offline..."}
Start-Sleep 120
#While (!(Test-Connection -Quiet -Delay 7 $DBServers)) {Write-Host "Waiting for $DBServers to come back online"}
LoggerLee "$DBServers back online!" success;
LoggerLee "`nSQL Server restart completed.`n" success;
Pause;
}
Catch
{
LoggerLee "Failed to restart SQL Server." error;
LoggerLee "Please manually restart the server and then Press Any Key to continue `n `n `n" warning;
$restarterror3 = "$_.Exception.Message";
LoggerLee "$restarterror3`n" error
Pause;
}
}
else {LoggerLee "`n`nCancelling SQL Server restart on $DBServers.`n`n" info}
}
########################################
# AppPool password changes
########################################
function UpdateAppPools
{
remove-job *
#LoggerLee "Updating Passwords for the App Pools....`n`n" Warning
### Grabs the accounts to be changed in the global variable of $accounts
$passwords = ConvertFrom-Csv $accounts # Acquired from parent function
$passwords | foreach {
$newpwd1 = $_.NewPassword
$username = $_.Username
#$newpassword = ConvertTo-SecureString -String $newpwd1 -AsPlainText -Force
LoggerLee -text "`n`nUpdating App Pool Passwords for the account: " info -linebreak nonewline
LoggerLee -text " $username...`n" info
Foreach ($server in $SPServers)
{
Try {
$SessionOption = New-PSSessionOption -IncludePortInSPN #Forces the port specified in the SPN
Invoke-Command -ComputerName $server -SessionOption $SessionOption -ErrorAction Stop -ScriptBlock { #Uses the session created above using the port in the SPN
$result = [PSCustomObject]@{
Success = $false
Message = $null
Completed = $false
Serv = $using:server
}
Import-Module WebAdministration
$applicationPools = Get-ChildItem IIS:\AppPools | where { $_.processModel.userName -eq "$Using:username" }
$Pools = $applicationPools.name
if($applicationPools)
{
$result.message += "`nAppPools using the $Using:username account are being updated on $Using:server...`n"
foreach($pool in $applicationPools)
{
#Using Unencrypted credentals due to errors with using the encrypted password
$un = $Using:username
$pw = $Using:newpwd1
Try
{
$pool.processModel.userName = "$un";
$pool.processModel.password = "$pw";
$pool.processModel.identityType = 3;
$result.message += "`nChanging password for '$($pool.name)' to $pw... `n" ;
$pool | Set-Item -ErrorAction Stop;
$result.message += "Password changed successfully!`n`n";
$result.success = $true
}
Catch
{
$result.message += "Failure on the password Change for $($pool.name) `n";
write-output $_.Exception.message;
$result.message += $_.Exception.Message;
$result.success = $false
}
}
}
else {
$result.success = $true;
$result.message = "No App Pool password to update on $using:server with account $using:username...`n"
}
$result
#Exit-PSSession
} -AsJob | out-null #-JobName UpdateAppPoolz | Out-Null
}
Catch
{
LoggerLee "Could not invoke a remote connection to $server!`n" warning;
LoggerLee "$($_.Exception.Message)" error;
}
}
$jobs = get-job # | wait-job -timeout 120
foreach ($job in $jobs){
WaitForJob $job.name "Completed"
$jobresult = $job | receive-job
if ($jobresult.success -eq $true)
{
#LoggerLee -text "Success on $($jobresult.serv)" warning;
LoggerLee -text "$($jobresult.message)" success
}
else
{
LoggerLee "This was a failure on $($jobresult.serv)" warning;
LoggerLee "$($jobresult.message)`n`n" error
}
#write-host $jobresult.success
}
remove-job *
}
}# End of App Pools Password changes
########################################
# Start any stopped App Pools
########################################
function Start-AppPools
{
#This may need to be modified to match whichever configuration is being used. This should be assigned as a paramater above
$accounts = (Import-Csv $InputFile | Where {(($_ -notmatch "mssql") -and ($_ -notmatch "agent") -and ($_ -notmatch "ssas") )} | ConvertTo-CSV -NoTypeInformation | % {$_ -replace '"',''}) | Out-String
LoggerLee "`n`n`nChecking for any App Pools that are enabled and not running....`n`n`n" info
$accounts = ConvertFrom-Csv $accounts
$accounts | foreach {
$username = $_.Username #Pulled from the Username column
#Pulled from a global variable-function that programatically pulls the SharePoint servers. Can be done via array
Foreach ($server in $SPServers)
{
#Write-Host "`n`n`n`nConnecting to $server to check for stopped App Pools using $username...`n" -ForegroundColor DarkGreen -BackgroundColor Cyan
Try {
$SessionOption = New-PSSessionOption -IncludePortInSPN #Forces the port specified in the SPN
Invoke-Command -ComputerName $server -SessionOption $SessionOption -ErrorAction Stop -ScriptBlock { #Uses the session created above using the port in the SPN
$result = [PSCustomObject]@{
Success = $false
Message = $null
Completed = $false
Serv = $using:server
}
Import-Module WebAdministration
# Pulls the app pool list based on the credentials and whether it is stopped.
$applicationPools = Get-ChildItem IIS:\AppPools | where { ($_.processModel.userName -eq "$Using:username") -and ($_.state -eq "Stopped") }
$Pools = $applicationPools.name # Not sure why this is here to be honest. Not used anywhere but left in case it's ever needed
if($applicationPools) # Only runs the below process if there are any app pools to run against (if not null)
{
foreach($pool in $applicationPools)
{
# Many powershell Commandlets and commands do not like variables pulled directly from outside of the invokation
$AppPool = $pool.name
#Write-Host "`nChecking to see if $AppPool pool is running on"$Using:server"" -BackGroundColor White -ForeGroundColor Blue
Try
{
$result.message += "Attempting start of '$AppPool'...`n";
(Start-WebAppPool -ErrorAction Stop -Name "$AppPool");
$result.message += "Completed successfully!`n`n";
$result.success = $true
}
Catch
{
$result.message += "*******Action Failed*********** `n";
$result.message += $_.Exception.Message;
$result.success = $false
}
}
}
Else {
$result.success = $true;
$result.message += "No Action to take on $using:server `n`n`n"
}
$result
} -AsJob | Out-Null
}
Catch {
LoggerLee "Could not invoke a remote connection to $server`n" warning;
LoggerLee "$_.Exception.Message" error
}
}
#Start of Jobs retrieval
$jobs = get-job # | wait-job -timeout 120
foreach ($job in $jobs){
WaitForJob $job.name "Completed"
$jobresult = $job | receive-job
if ($jobresult.success -eq $true)
{
#LoggerLee -text "Success on $($jobresult.serv)" warning;
LoggerLee -text "$($jobresult.message)" success
}
else
{
LoggerLee "This was a failure on $($jobresult.serv)" warning;
LoggerLee "$($jobresult.message)`n`n" error
} }
# Clears or resets variables
$accounts = $null
remove-job *
}}
########################################
# Windows Services password changes
########################################
function Set-WindowsServicesCreds
{
LoggerLee "Changing Passwords for any Windows services that are using the service accounts...`n" Warning
Get-Accounts
### Grabs the accounts to be changed in the global variable of $accounts
$passwords = ConvertFrom-Csv $accounts # Acquired from parent function
$passwords | foreach {
$newpwd1 = $_.NewPassword
$username = $_.Username
$newpassword = ConvertTo-SecureString -String $newpwd1 -AsPlainText -Force
Foreach ($server in $SPServers)
{
Try {
$SessionOption = New-PSSessionOption -IncludePortInSPN
Invoke-Command -ComputerName "$server" -SessionOption $SessionOption -ErrorAction Stop -ScriptBlock {
$result = [PSCustomObject]@{
Success = $false
Message = $null
Completed = $false
Serv = $using:server
}
$result.message += "Checking for services that use the account: $Using:username on $Using:server... `n"
$WinServices = Get-CimInstance win32_service | Where {$_.StartName -eq "$Using:username"}
if($WinServices)
{
foreach ($s in $WinServices)
{
if($s)
{
$serv = $s.Name # Must use short name and cannot use the '$Using:' method in CIM commands
$pass = $Using:newpwd1 # Cannot use '$Using:' and Encrypted password for CIM methods **CONFIRMED**
Try
{
$result.message += "Changing password for '$($s.Name)' to $Using:newpwd1 on $Using:server...`n";
Invoke-CimMethod -ErrorAction stop -Name Change -Arguments @{StartPassword="$pass"} -Query "Select * from Win32_service where Name='$serv'" | out-file "c:\allowed\scripts\CIMresults.txt" ; #Verify a '0' status code in this file if necessary (0 means successful)
$result.message += "Completed Successfully! `n`n";
$result.success = $true
}
Catch
{
$result.message += "*******Action Failed*********** `n";
$result.message += $_.Exception.Message;
$result.success = $false
}
}
}
}
Else {
$result.success = $true;
$result.message += "No Action to take on $using:server `n`n"
}
$result
} -AsJob | Out-Null
}
Catch {
LoggerLee "Could not invoke a remote connection to $server`n" warning;
LoggerLee "$_.Exception.Message" error
}
}
#Start of Jobs retrieval
$jobs = get-job # | wait-job -timeout 120
foreach ($job in $jobs){
WaitForJob $job.name "Completed"
$jobresult = $job | receive-job
if ($jobresult.success -eq $true)
{
LoggerLee -text "$($jobresult.message)" success
}
else
{
LoggerLee "This was a failure on $($jobresult.serv)" warning;
LoggerLee "$($jobresult.message)`n`n" error
} }
# Clears or resets variables
$accounts = $null
remove-job *
}}
###########################################################################
# (SharePoint) Restart Windows Services
###########################################################################
function Restart-WindowsServices
{
#Get List of accounts
$accounts = (Import-Csv $InputFile | Where {(($_ -notmatch "mssql") -and ($_ -notmatch "agent") -and ($_ -notmatch "ssas") )} | ConvertTo-CSV -NoTypeInformation | % {$_ -replace '"',''}) | Out-String
LoggerLee "`n`n`nRestarting Windows services....`n`n" warning
#Loops a list of user accounts to check on each server
$passwords = ConvertFrom-Csv $accounts # Acquired from parent function
$passwords | foreach {
$username = $_.Username
foreach ($srv in $SPServers)
{
Try {
#Write-Host "`n`n`n`nConnecting to $srv to check for stopped services using $username...`n" -ForegroundColor DarkGreen -BackgroundColor Cyan
$SessionOption = New-PSSessionOption -IncludePortInSPN
Invoke-Command -ComputerName $srv -SessionOption $SessionOption -ErrorAction Stop -ScriptBlock {
$result = [PSCustomObject]@{
Success = $false
Message = $null
Completed = $false
Serv = $using:srv
}
$WinServices = Get-CimInstance win32_service | Where {(($_.StartName -eq "$Using:username") -and ($_.State -eq "Running") -and ($_.StartMode -ne "Disabled") )}
if($WinServices)
{
foreach ($srvc in $WinServices)
{
$service = $srvc.DisplayName
$svc = $srvc.Name
Try
{
Restart-Service -DisplayName $service -ErrorAction Stop;
$result.message += "`nSuccessfully Restarted '$service' on $Using:srv `n`n" ;
$result.success = $true
}
Catch
{
$result.message += "`n`nService could not be restarted on $using:srv"
$result.message += $_.Exception.Message;
$result.success = $false
}
}
}
Else {
$result.success = $true;
$result.message += "No Action to take on $using:srv `n`n"
}
$result
} -AsJob | Out-Null
}
Catch {
LoggerLee "Could not invoke a remote connection to $srv " warning;
LoggerLee "$_.Exception.Message" error
}
}
#Start of Jobs retrieval
$jobs = get-job # | wait-job -timeout 120
foreach ($job in $jobs){
WaitForJob $job.name "Completed"
$jobresult = $job | receive-job
if ($jobresult.success -eq $true)
{
LoggerLee -text "$($jobresult.message)" success
}
else
{
LoggerLee "This was a failure on $($jobresult.serv)" warning;
LoggerLee "$($jobresult.message)`n`n" error
} }
# Clears or resets variables
$accounts = $null
remove-job *
}}
########################################
# Recycle SharePoint specific AppPools
########################################
function Recycle-AppPools
{
remove-job *
#This may need to be modified to match whichever configuration is being used. This should be assigned as a paramater above
$accounts = (Import-Csv $InputFile | Where {(($_ -notmatch "mssql") -and ($_ -notmatch "agent") -and ($_ -notmatch "ssas") )} | ConvertTo-CSV -NoTypeInformation | % {$_ -replace '"',''}) | Out-String
LoggerLee "`nRecycling / Restarting any SharePoint AppPools....`n`n"
$accounts = ConvertFrom-Csv $accounts
$accounts | foreach {
$username = $_.Username #Pulled from the Username column
#Pulled from a global variable-function that programatically pulls the SharePoint servers. Can be done via array
Foreach ($server in $SPServers)
{
Try {
$SessionOption = New-PSSessionOption -IncludePortInSPN #Forces the port specified in the SPN
Invoke-Command -ComputerName $server -SessionOption $SessionOption -ErrorAction Stop -ScriptBlock { #Uses the session created above using the port in the SPN
$result = [PSCustomObject]@{
Success = $false
Message = $null
Completed = $false
Serv = $using:server
}
Import-Module WebAdministration
# Pulls the app pool list based on the credentials and whether it is stopped.
$applicationPools = Get-ChildItem IIS:\AppPools | where { ($_.processModel.userName -eq "$Using:username") -and ($_.state -eq "Started") }
$Pools = $applicationPools.name # Not sure why this is here to be honest. Not used anywhere but left in case it's ever needed
if($applicationPools) # Only runs the below process if there are any app pools to run against
{
foreach($pool in $applicationPools)
{
# Many powershell Commandlets and commands do not like variables pulled directly from outside of the invokation
$AppPool = $pool.name
#Write-Host "`nChecking to see if $AppPool pool is running on"$Using:server"" -BackGroundColor White -ForeGroundColor Blue
Try
{
(Restart-WebAppPool -ErrorAction Stop -Name "$AppPool");
$result.message += "`nRecycled $AppPool on $Using:server`n" ;
$result.success = $true
}
Catch
{
$result.message += "`n*******Action Failed*********** `n";
$result.message += $_.Exception.Message;
$result.success = $false
}
}
}
Else
{
$result.success = $true;
$result.message += "No Action to take on $using:server `n`n`n"
}
$result
} -AsJob | Out-Null
}
Catch {
LoggerLee "Could not invoke a remote connection to $server`n" warning;
LoggerLee "$_.Exception.Message" error
}
}
#Start of Jobs retrieval
$jobs = get-job # | wait-job -timeout 120
foreach ($job in $jobs){
WaitForJob $job.name "Completed"
$jobresult = $job | receive-job
if ($jobresult.success -eq $true)
{
LoggerLee -text "$($jobresult.message)" success
}
else
{
LoggerLee "This was a failure on $($jobresult.serv)" warning;
LoggerLee "$($jobresult.message)`n`n" error
} }