Posts Tagged ‘PowerShell’

Posted by IsaacBlum at 7 November 2011

Category: Business, For The Greater Good, Free Help, Microsoft, PowerShell

Tags: ,

Enable is the first PS command. The second is used if you would like to use CredSSP creds. Clicking the links will take you to the Technet article.

Enable-PsRemoting -Force

Enable-WSManCredSSP

Original Post: http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spfilecollection.aspx

**Please note** I didn’t attempt to “dispose”, so make sure to add it…

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$PSSnapin = Add-PsSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue | Out-Null
clear
 
$org = "http://blueleader"
$dest = "http://redleader"
 
$orgLibrary = (Get-SPWeb $org).Folders["Documents"]
$destLibrary = (Get-SPWeb $dest).Folders["Documents"]
$destFiles = $destLibrary.Files
foreach ($file in $orgLibrary.Files)
{
	$curFile = $file.OpenBinary()
	$destURL = $destFiles.Folder.Url + "/" + $file.Name
	$destFiles.Add($destURL, $curFile, $true)
}

 

Posted by IsaacBlum at 24 August 2011

Category: Business, Cloud, For The Greater Good, Free Help, Microsoft, PowerShell

Tags: , , ,

It has come to my attention that there is still a handful of folks out there writing PowerShell with NOTEPAD…. I won’t name names… But you all know who you are. :) :)

Anyway I use a free tool from Quest software called PowerGUI. See the link to the latest build http://community-downloads.quest.com/powergui/Release/3.0/PowerGUI.3.0.0.2015.msi or http://powergui.org This is the tool that you “never leave home without”. It’s just like visual studio in the sense that you can step into code and debug variables, for each loops, you name it, it can do it. Please let me know if you have any questions.

BTW, a solid second place winner is… Microsoft Windows PowerShell ISE http://technet.microsoft.com/en-us/library/dd315244.aspx

The script enumerates a folder structure based off the input section of the PowerShell script. It then detects all .wsp files in any folder at the root of the folder and below. Once the list of files is compiled by PowerShell, it begins to either upgrade or installs each detected wsp. The script has a bit of logic when attempting an install or upgrade. If the PowerShell script detects that the solution is already deployed to the farm, it will first attempt to retract the solution, once completed it then removes the solution before it attempts to install and deploys the feature to all web applications.

 

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
######################################
######## Set Variables ###############
######################################
$InstallDIR = "C:\install"
 
######################################
#### CODE, No Changes Necessary ######
######################################
Write-Host "Working, Please wait...."
Add-PSSnapin microsoft.sharepoint.powershell -ErrorAction SilentlyContinue
 
$Dir = get-childitem $InstallDIR -Recurse
$WSPList = $Dir | where {$_.Name -like "*.wsp*"}
Foreach ($wsp in $WSPList )
{
	$WSPFullFileName = $wsp.FullName
	$WSPFileName = $wsp.Name
	clear
	Write-Host -ForegroundColor White -BackgroundColor Blue "Working on $WSPFileName" 
 
	try
	{
		Write-Host -ForegroundColor Green "Checking Status of Solution"
		$output = Get-SPSolution -Identity $WSPFileName -ErrorAction Stop
	}
	Catch
	{
		$DoesSolutionExists = $_
	}
	If (($DoesSolutionExists -like "*Cannot find an SPSolution*") -and ($output.Name -notlike  "*$WSPFileName*"))
	{
		Try
		{
			Write-Host -ForegroundColor Green "Adding solution to farm"
			Add-SPSolution "$WSPFullFileName" -Confirm:$false -ErrorAction Stop | Out-Null
 
			Write-Host -ForegroundColor Green "Checking Status of Solution"
			$output = Get-SPSolution -Identity $WSPFileName -ErrorAction Stop
			$gobal = $null
			if ($output.Deployed -eq $false)
			{
				try
				{
					Write-Host -ForegroundColor Green "Deploy solution to all Web Apps, will skip if this solution is globally deployed"
					Install-SPSolution -Identity "$WSPFileName" -GACDeployment -AllWebApplications -Force -Confirm:$false -ErrorAction Stop | Out-Null
				}
				Catch
				{
					$gobal = $_
				}
				If ($gobal -like "*This solution contains*")
				{
					Write-Host -ForegroundColor Green "Solution requires global deployment, Deploying now"
					Install-SPSolution -Identity "$WSPFileName" -GACDeployment -Force -Confirm:$false -ErrorAction Stop | Out-Null
				}
			}
 
			Sleep 1
			$dpjobs = Get-SPTimerJob | Where { $_.Name -like "*$WSPFileName*" }
			If ($dpjobs -eq $null)
    		{
        		Write-Host -ForegroundColor Green "No solution deployment jobs found"
    		}
			Else
			{
				If ($dpjobs -is [Array])
				{
					Foreach ($job in $dpjobs)
					{
						$jobName = $job.Name
						While ((Get-SPTimerJob $jobName -Debug:$false) -ne $null)
						{
							Write-Host -ForegroundColor Yellow -NoNewLine "."
							Start-Sleep -Seconds 5
						}
						Write-Host
					}
				}
    			Else
    			{
					$jobName = $dpjobs.Name
					While ((Get-SPTimerJob $jobName -Debug:$false) -ne $null)
					{
						Write-Host -ForegroundColor Yellow -NoNewLine "."
						Start-Sleep -Seconds 5
					}
					Write-Host
    			}
			}
		}
		Catch
		{
			Write-Error $_
			Write-Host -ForegroundColor Red "Skipping $WSPFileName, Due to an error"
			Read-Host
		}
	}
	Else
	{
		$skip = $null
		$tryagain = $null
		Try
		{
			if ($output.Deployed -eq $true)
			{
			Write-Host -ForegroundColor Green "Retracting Solution"
			Uninstall-SPSolution -AllWebApplications -Identity $WSPFileName -Confirm:$false -ErrorAction Stop
			}
		}
		Catch
		{
			$tryagain = $_
		}
		Try
		{
			if ($tryagain -ne $null)
			{
				Uninstall-SPSolution -Identity $WSPFileName -Confirm:$false -ErrorAction Stop
			}
		}
		Catch
		{
			Write-Host -ForegroundColor Red "Could not Retract Solution"
		}
 
		Sleep 1
		$dpjobs = Get-SPTimerJob | Where { $_.Name -like "*$WSPFileName*" }
		If ($dpjobs -eq $null)
    	{
        	Write-Host -ForegroundColor Green "No solution deployment jobs found"
    	}
		Else
		{
			If ($dpjobs -is [Array])
			{
				Foreach ($job in $dpjobs)
				{
					$jobName = $job.Name
					While ((Get-SPTimerJob $jobName -Debug:$false) -ne $null)
					{
						Write-Host -ForegroundColor Yellow -NoNewLine "."
						Start-Sleep -Seconds 5
					}
					Write-Host
				}
			}
    		Else
    		{
				$jobName = $dpjobs.Name
				While ((Get-SPTimerJob $jobName -Debug:$false) -ne $null)
				{
					Write-Host -ForegroundColor Yellow -NoNewLine "."
					Start-Sleep -Seconds 5
				}
				Write-Host
    		}
		}		
 
		Try
		{
			Write-Host -ForegroundColor Green "Removing Solution from farm"
			Remove-SPSolution -Identity $WSPFileName -Confirm:$false -ErrorAction Stop
		}
		Catch
		{
			$skip = $_
			Write-Host -ForegroundColor Red "Could not Remove Solution"
			Read-Host
		}
		if ($skip -eq $null)
		{
			Try
			{
				Write-Host -ForegroundColor Green "Adding solution to farm"
				Add-SPSolution "$WSPFullFileName" -Confirm:$false -ErrorAction Stop | Out-Null
				$gobal = $null
				try
				{
					Write-Host -ForegroundColor Green "Deploy solution to all Web Apps, will skip if this solution is globally deployed"
					Install-SPSolution -Identity "$WSPFileName" -GACDeployment -AllWebApplications -Force -Confirm:$false -ErrorAction Stop | Out-Null
				}
				Catch
				{
					$gobal = $_
				}
				If ($gobal -like "*This solution contains*")
				{
					Write-Host -ForegroundColor Green "Solution requires global deployment, Deploying now"
					Install-SPSolution -Identity "$WSPFileName" -GACDeployment -Force -Confirm:$false -ErrorAction Stop | Out-Null
				}
			}
			Catch
			{
				Write-Error $_
				Write-Host -ForegroundColor Red "Skipping $WSPFileName, Due to an error"
				Read-Host
			}
 
			Sleep 1
			$dpjobs = Get-SPTimerJob | Where { $_.Name -like "*$WSPFileName*" }
			If ($dpjobs -eq $null)
    		{
        		Write-Host -ForegroundColor Green "No solution deployment jobs found"
    		}
			Else
			{
				If ($dpjobs -is [Array])
				{
					Foreach ($job in $dpjobs)
					{
						$jobName = $job.Name
						While ((Get-SPTimerJob $jobName -Debug:$false) -ne $null)
						{
							Write-Host -ForegroundColor Yellow -NoNewLine "."
							Start-Sleep -Seconds 5
						}
						Write-Host
					}
				}
    			Else
    			{
					$jobName = $dpjobs.Name
					While ((Get-SPTimerJob $jobName -Debug:$false) -ne $null)
					{
						Write-Host -ForegroundColor Yellow -NoNewLine "."
						Start-Sleep -Seconds 5
					}
					Write-Host
    			}
			}
	}
	Else
	{
		Write-Host -ForegroundColor Red "Cannot Install $WSPFileName, Please try manually"
		Read-Host
	}
}
}

Use case: Needed to understand the current security layout of a SharePoint site that was migrated from 2007 to 2010. The customer didn’t know what permissions were set where. They needed a way to report on how each site was granting or restricting permissions.

*Notes:

  • I’m not disposing of any objects. Sure I understand this is bad, but the intention of this script is to be run one time in a test environment. So if you plan on running this in production, I would suggest adding the dispose objects.
  • Script is set to put the raw xml file at the C:\, you change this in the .ps1 file.
  • Runs against all web applications in farm minus central admin.
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
$logfilepath = "C:\"
 
##Create Table - ScanTable
$ScanTable = New-Object system.Data.DataTable "ScanTable"
$col1 = New-Object system.Data.DataColumn ("URL", [string])
$col2 = New-Object system.Data.DataColumn ("Member", [string])
$col3 = New-Object system.Data.DataColumn ("BasePermissions", [string])
$col4 = New-Object system.Data.DataColumn ("PermFriendlyName", [string])
$col5 = New-Object system.Data.DataColumn ("User_Group", [string])
$ScanTable.columns.add($col1)
$ScanTable.columns.add($col2)
$ScanTable.columns.add($col3)
$ScanTable.columns.add($col4)
$ScanTable.columns.add($col5)
 
$PermLevels = @{}
 
function getsec
{
	Add-PSSnapin microsoft.sharepoint.powershell -ErrorAction SilentlyContinue
 
	$PortalName = Get-SPWebApplication | select DisplayName
	foreach ($p in $PortalName)
	{
		$webapp = Get-SPWebApplication | ? {$_.DisplayName -eq $p.Displayname}
		#$webapp = Get-SPWebApplication | ? {$_.DisplayName -eq "SharePoint"}
		foreach ($s in $webapp.Sites)
		{
			foreach ($web in $s.AllWebs)
			{
				foreach ($r in $web.roles)
				{
					$permpermmask = $r.PermissionMask
					$permname = $r.Name
					$PermLevels.Add("$permpermmask", "$permname")
					trap [Exception] {continue;}
				}
				$red = $web.HasUniqueRoleDefinitions
				foreach ($perm in $web.Permissions)
				{
					#$perm | select *
					#$perm.PermissionMask
					$permpermmaskcurrent = $perm.PermissionMask
					$level = $PermLevels.Get_Item("$permpermmaskcurrent")
					if ($perm.xml -like "*GroupName*")
					{
						$usergroup = "SharePoint Group"
					}
					if ($perm.xml -like "*UserLogin*")
					{
						$usergroup = "AD User"
					}
					$MemberIsADGroup = $perm.Member.IsDomainGroup
					if ($MemberIsADGroup -eq $true)
					{
						$usergroup = "AD Group"
					}
					$output = $ScanTable.Rows.Add($web.url, $perm.Member, $perm.BasePermissions, $level, $usergroup)
				}
			}
		}
	}
	$ScanTable.WriteXML("$logfilepath\SecurityReport.xml")
}
getsec

I believe I got the base of this script from the AutoSPInstaller Project on CodePlex. I enhanced it to enable object cache on all web apps. Just fill in your variables on lines 1 and 2. *Note many of my customers tend to create long user names for these two accounts. Make sure to get the Pre-Compatibility 2000 username, its will be shoter in length than the full username. The script will blow up if you use the longer one. Thanks.

 

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
$SuperUserAcc = "domain\SPSObjectCacheF"
$SuperReaderAcc = "domain\SPSObjectCacheR"
 
$PortalName = Get-SPWebApplication | select DisplayName
 
function Set-WebAppUserPolicy($webApp, $userName,$displayName, $perm) {
    [Microsoft.SharePoint.Administration.SPPolicyCollection]$policies = $webApp.Policies
    [Microsoft.SharePoint.Administration.SPPolicy]$policy = $policies.Add($userName, $displayName)
    [Microsoft.SharePoint.Administration.SPPolicyRole]$policyRole = $webApp.PolicyRoles | where {$_.Name -eq $perm}
    if ($policyRole -ne $null) {
        $policy.PolicyRoleBindings.Add($policyRole)
    }
    $webApp.Update()
}
 
function ConfigureObjectCache
{
	foreach ($p in $PortalName)
	{
		$site = $p.DisplayName
		Try
		{
   			Write-Host -ForegroundColor White "- Applying object cache..."
        		$webapp = Get-SPWebApplication | ? {$_.DisplayName -eq $p.Displayname}
 
        		If ($webapp -ne $Null)
        		{
				Write-Host -ForegroundColor White " - Applying object cache to $site ..."
           			$webapp.Properties["portalsuperuseraccount"] = $SuperUserAcc
	       			Set-WebAppUserPolicy $webApp $SuperUserAcc "Super User (Object Cache)"  "Full Control"
 
           			$webapp.Properties["portalsuperreaderaccount"] = $SuperReaderAcc
	       			Set-WebAppUserPolicy $webApp $SuperReaderAcc "Super Reader (Object Cache)" "Full Read"
           			$webapp.Update()        
    	   			write-Host -ForegroundColor White "- Done."
        		}
		}
		Catch
		{
			$_
			Write-Warning "- An error occurred applying object cache to portal."
		}
	}
}
 
ConfigureObjectCache

Adding FAST Search to an existing SharePoint 2010 farm, you may notice that your existing site collections do not have “keywords, site promotion and demotion, user context” functions in the site collection administration section. Well there is a good reason for that…. The feature that activates these functions is not enabled. The feature ID is “5EAC763D-FBF5-4d6f-A76B-EDED7DD7B0A5″ . I had seen this behavior in my development environment but never tried to understand why. I would just create a new site collection and boom everything was back to normal. J A quick Google search found this blog. http://www.neilrichards.net/blog/?p=149  so thanks NEIL! 

Before

After

The only credit I can take is the PowerShell code below that enumerates through all the web applications and their site collections and activates the feature. Thanks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Start-SPAssignment -Global
$red = Get-SPWebApplication
foreach ($r in $red)
{
	$rtrim = $r.url
	$rurl = $rtrim.trim("/")
	$rurl
	$blue = Get-SPSite "$rurl(|)" -Limit All -regex
	Foreach ($b in $blue)
	{
		$b.url
		$siteWithNoFastFeatures = get-SPSite $b.url
		$siteWithNoFastFeatures.Features.Add("5EAC763D-FBF5-4d6f-A76B-EDED7DD7B0A5")
	}
}
Stop-SPAssignment -Global

Run these PowerShell Commands:

 

1
2
$StartUsageHealthDataCollectionProxy  = Get-SPServiceApplicationProxy | ? {$_.TypeName -like "*Usage and Health*"}
$StartUsageHealthDataCollectionProxy.Provision()

A client needed a way to remove old domain users from their SharePoint 2010 farm. There was a company merger and they did not want the old domain users showing in the sites.

Enter the root site collection and the search parameter ex: domain and done.

** you might notice a table being created… I left this in here, but its not really used. The client had some additional requirements, that I have not included in this script.

 

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
## Reference to SharePoint DLL
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
 
##Ask for WebApp Root url to enumerate or scope scan
Write-Host "Please enter root url of WebApplication, ex: http://contoso"
$siteurl = Read-Host "Value "
Write-Host "Please enter the search parameter, ex: contoso "
$searchP = Read-Host "Value "
 
##Create Table - ScanTable
$ScanTable = New-Object system.Data.DataTable "ScanTable"
$col1 = New-Object system.Data.DataColumn ("LoginName", [string])
$col2 = New-Object system.Data.DataColumn ("URL", [string])
$ScanTable.columns.add($col1)
$ScanTable.columns.add($col2)
 
##Returning info for use in remainder of script
$webapp = [Microsoft.SharePoint.Administration.SPWebApplication]::Lookup($siteurl)
##Start looping through the sites collections
foreach ($site in $webapp.Sites)
{
    $spSite = new-object Microsoft.SharePoint.SPSite($site.url)
	$spWeb = $spSite.OpenWeb()
 
	##Save file path, guid, and title of each closed webpart
	foreach ($_.LoginName in $spSite.RootWeb.SiteUsers | select LoginName)
	{
	if ($_.LoginName -like "*$searchP*")
	{
	$output = $ScanTable.Rows.Add($_.LoginName, $site.url)
	$spWeb.SiteUsers.Remove($_.LoginName)
	}
	}
 
	##Clean Up
    $spSite.Dispose()
    $spWeb.Dispose()
}
 
##Write txt file
Write-Output $ScanTable | select URL | Sort-Object URL -Unique | Out-File C:users.txt -Append

By default the SharePoint Trace service runs as local system.This script will fix that. 

1. Create a SharePoint 2010 Trace Account. Ex: SPTrace

2. Edit lines 2 and 3 of the PowerShell script.

3. Run script on each server in farm. (not FAST or SQL servers) a. PS C:UsersspinstallDesktop> .TraceAccountFix.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
# Trace Account Details
$TraceAccount = "DomainSPTrace"
$TraceAcctPWD = "Enter The password here"
$SecTraceAcctPWD = (ConvertTo-SecureString $TraceAcctPWD -AsPlainText -force)
 
# Formatting
$TraceAccountDomain,$TraceAccountUser = $TraceAccount -Split "\"
 
# Get the tracing service.
$farm = Get-SPFarm
$tracingService = $farm.Services | where {$_.Name -eq "SPTraceV4"}
 
$Cred_TraceAcct = New-Object System.Management.Automation.PsCredential $TraceAccount,$SecTraceAcctPWD
 
## Add Managed Account for Trace Account
$ManagedAccountTrace = Get-SPManagedAccount | Where-Object {$_.UserName -eq $TraceAccount}
If ($ManagedAccountTrace -eq $NULL) 
{ 
	Write-Host -ForegroundColor White "- Registering managed account" $TraceAccount
	New-SPManagedAccount -Credential $Cred_TraceAcct | Out-Null 
}
Else {Write-Host -ForegroundColor White "- Managed account $TraceAccount already exists, continuing."}
 
 
# Get the managed account.
$managedAccount = Get-SPManagedAccount "$TraceAccount"
If ($tracingService.ProcessIdentity.ManagedAccount -notlike "*$managedAccount*"){
 
# Set the tracing service to run under the managed account.
$tracingService.ProcessIdentity.CurrentIdentityType = "SpecificUser"
$tracingService.ProcessIdentity.ManagedAccount = $managedAccount
$tracingService.ProcessIdentity.Update()
 
# This actually changes the "Run As" account of the Windows service.
$tracingService.ProcessIdentity.Deploy()
}
 
Try{
([ADSI]"WinNT://$env:COMPUTERNAME/Performance Log Users,group").Add("WinNT://$TraceAccountDomain/$TraceAccountUser")
}
catch {Write-Host -ForegroundColor White " - $TraceAccount is already an in the Performance Log Users group, continuing."}
 
Write-Host "All Done"
  • Archives

  • Tags

  • Subscribe
  • Pages

  • More

  • Disclaimer…

    This is my personal weblog. The opinions expressed herein are my own and are not representative of any 3rd party influence. The owner of this blog reserves the right to edit or delete any comments submitted to this blog without notice if they are deemed to be spam, offensive or otherwise inappropriate. The owner of this blog makes no representations as to the accuracy or completeness of any information on this site or found by following any link on this site. The owner will not be liable for any errors or omissions in this information nor for the availability of this information. The owner will not be liable for any losses, injuries, or damages from the display or use of this information.


    Lastly, I do my best to document my sources if the article is not of my own creation. If I have missed or forgotten to source your work. I would love feedback via the comments section. Thank you.

DreamHost promos
SiteLock