PowerShell Get SharePoint Person or Group Field

This one drove me CRAZY!

Simple question, how do you get people or groups from a SharePoint People or Group field.

Add-PsSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

$site = Get-SPweb "http://www.sharepointed.com"

				$mList=$site.Lists["ListName"]
                                #you will want to provide a valid ID here:
				$item = $mList.GetItemById(<strong>"4"</strong>)
				$users=$item["MyPersonOrGroupField"]
				
				#build array of our Person or Groups
				$PeopleOrGroup = New-Object System.Collections.ArrayList
				
				If($PeopleOrGroup.Count -ge 0)
				{
					foreach($blah in $PeopleOrGroup)
						{
						 $parseUsr = $blah.ToString().Split('#')[1]
						 $PeopleOrGroup.add($parseUsr)					 
						}
				}

                                #now if you want to access our newly created array
                                Foreach($pg in $PeopleOrGroup)
                                {
                                     write-host $pg
                                }
                                


*Update*
Found another way to get this done!

foreach($blah in $PeopleOrGroup)
       {
	 $PeopleOrGroup.add($site.Users.GetByID($blah.LookupId))					 
       }

How to control permissions from a central List

Say you have  your site setup where every one of your customers has a sub site.  How could you easily manage the permissions on those sites?  What I have adopted is, creating a List where the sub sites are created from and managed.

Using the workflow actions from ilovesharepoint I’m doing the following.

1. Setup a Contact List (Customers) with these additional fields: Customer Site (Hyperlink), UserPermissions(Person or Group), Customer Status (Choice)

2. Using the ilovesharepoint Create a new site action, create a new customer site.  Using the Output variable of this action, write the URL to our Customer Site field.

3. Use the ilovesharepoint Execute PowerShell action to run our PowerShell script.


Add-PsSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
 $site = Get-SPweb "http://www.sharepointed.com"

$mList=$site.Lists["Customers"]
 #Here you will want to add the ID of the item calling the workflow.
 #Simply remove [%Current Item:ID%], click on Add or Change Lookup, and add the ID field
 $item = $mList.GetItemById([%Current Item:ID%])
 $ActionType=$Item["Customer Status"]
 $CustomerSite= new-object Microsoft.SharePoint.SPFieldUrlValue($item["Customer Site"])
 $ClientSiteURL=$CustomerSite.URL
 $users=$item["UserPermissions"]

#build array of User Permissions
 $PowerUsr = New-Object System.Collections.ArrayList

foreach($usr in $users)
	{	 
						
		 $sUser = $usr.User
		 if($sUser -ne $null)
		 {
			$parseUsr = $site.SiteUsers.GetByID($usr.LookupId)
		 }
		 else
		 {
			$parseUsr = $usr.LookupValue
		 }
						 
		$PowerUsr.add($parseUsr)					 
	}

$web = Get-SPWeb $ClientSiteURL
$SDlist = $web.Lists["Shared Documents"]

#break role inheritance
 $SDlist.BreakRoleInheritance($true)

#remove all permissions from the List
 foreach ($assignment in $SDlist.RoleAssignments)
 {
 $assignment.RoleDefinitionBindings.RemoveAll();
 $assignment.Update();
 }

# Customer Status = Active
 If ($ActionType -eq "Active")
 {
 		if($PowerUsr.Count -ge 0)
		{
			foreach($Ausr in $PowerUsr)
				{
					$siteUsr = ""
					$account = ""
					$siteUsr = $site.SiteUsers[$Ausr]
					$siteGroup = $web.SiteGroups[$Ausr]
					
					if($siteUsr -ne $null)
					{
						$role = $web.RoleDefinitions["Read"]
						$assignment = New-Object Microsoft.SharePoint.SPRoleAssignment($siteUsr)
						$assignment.RoleDefinitionBindings.Add($role)
						$SDlist.RoleAssignments.Add($assignment)
						$web.RoleAssignments.Add($assignment)

					}
					else
					{
						$role = $web.RoleDefinitions["Read"]
						$assignment = New-Object Microsoft.SharePoint.SPRoleAssignment($siteGroup)
						$assignment.RoleDefinitionBindings.Add($role)
						$SDlist.RoleAssignments.Add($assignment)
						$web.RoleAssignments.Add($assignment)
					}
				}
		}
 }

# Customer Status = Not Active
 If ($ActionType -eq "Not Active")
 {
 if($PowerUsr.Count -ge 0)
 {
 foreach($Ausr in $PowerUsr)
 {
 $account = $web.SiteGroups[$Ausr]
 $role = $web.RoleDefinitions["Read"]

$assignment = New-Object Microsoft.SharePoint.SPRoleAssignment($account)
 $assignment.RoleDefinitionBindings.Add($role)
 $SDlist.RoleAssignments.Add($assignment)
 }
 }
 }

$SDlist.Update()
$web.Dispose()
$site.Dispose()

The script gets the URL of our sub site and permissions we are wanting to set on the Shared Documents library. By setting the Customer Status to Active or Not Active, the script will change the permissions accordingly.

*update*
Updated the script to work with users and groups.

Run Warmup Script on Startup

Recently ran across a SharePoint install that had links to all the web apps in the Startup folder on the WFE box.  First thought was, PowerShell that mess!

First you will need to create a batch file to call the PowerShell warmup script.  The batch file will need to live in your Startup folder. By doing this, the script will run on server startup.

*update*  what if you want to pause / delay the batch file? Simply add a “timeout /t 5” after the @echo off statement.  *remove the quotes and 5 is measured in seconds.*

@echo off
timeout /t 5
powershell.exe d:\PowerShellScripts\warmup.ps1

The PowerShell warmup script:


Add-PSSnapin Microsoft.SharePoint.PowerShell;

function Get-WebPage([string]$url)
{
 $wc = new-object net.webclient;
 $wc.credentials = [System.Net.CredentialCache]::DefaultCredentials;
 $pageContents = $wc.DownloadString($url);
 $wc.Dispose();
 return $pageContents;
}

Get-SPAlternateUrl -Zone Default | foreach-object {
 write-host $_.IncomingUrl;
 $html = Get-WebPage -url $_.IncomingUrl;
}

warmup script was created by Jon Badgett

http://www.jonthenerd.com/2011/04/19/easy-sharepoint-2010-warmup-script-using-powershell/

You are not allowed to respond again to this survey

Error: You are not allowed to respond again to this survey.

Either the user has already taken the survey or they started taking the survey and never finished.

You can try going in and deleting what they have already done.  Or allow users to take the survey more than once.

How to allow users to take survey again:

Your Survey –>  Survey Settings –> General Settings

Survey Option –> Allow multiple responses –> Yes

Then click save.

 

PowerShell Get a List of Site Templates

If you need to script out a list of available site templates, here is the answer.


Add-PSSnapin Microsoft.SharePoint.PowerShell –erroraction SilentlyContinue
$site = Get-SPSite "http://www.sharepointed.com/tacoSiteCollection"
$web = $site.RootWeb
$listTemplates = $site.GetCustomListTemplates($web)

foreach($xx in $listTemplates)
 {
 Write-Host $xx.FeatureId
 }

$site.Dispose()

PowerShell Calculated Column Create and Edit

How do you create a calculated column using PowerShell?  In my example, I’m creating a new field called Calculated Date Field, setting the formula, then setting the output type to DateTime.

How do I build the formula?  Go into your list, add a new calculated column, create your formula, test the formula.  If it works, copy the formula and delete the column.


$site = Get-SPweb "http://sharepointed.com/site/salsa/"

$mList=$site.Lists["Nacho"]

 $mList.Fields.Add("Calculated Date Field", "Calculated", 0)
 $SPField = $mList.Fields.GetField("Calculated Date Field")
 $SPField.Formula="=DATE(YEAR([Document Date])+7,MONTH([Document Date])+0,DAY([Document Date])+0)"
 $SPField.OutputType="DateTime"
 $SPField.Update()

$site.Dispose()

PowerShell Get SharePoint Page Layouts

I was having an issue with a script and needed to find my available page layouts. Below is the script you will need to run to find the available page layouts for a given site.

$web = Get-SPweb "http://sharepointed.com/sites/taco"

		$pubWeb =[Microsoft.SharePoint.Publishing.PublishingWeb]::GetPublishingWeb($web)
		$pl = $pubWeb.GetAvailablePageLayouts()
		foreach($p in $pl)
		{
			Write-Host $p.Name
		}
$site.Dispose()

PowerShell Get Sub Webs of a Web

If you are looking for a way to get all of the subsites for a given site, PowerShell can help.

Add-PSSnapin Microsoft.SharePoint.PowerShell –erroraction SilentlyContinue

$spWeb = Get-SPweb "http://sharepointed.com/sites/taco"

	foreach($subSite in $spWeb.Webs)
		{
			$subSite.Title
			$subSite.Dispose()
		}

$spWeb.Dispose()

1. add the SharePoint Snapin
2. get the site that we want to dig into.
3. loop on each subsite
3.1. display the site title
3.2. close the connection to the subsite.
4. close the connection to the site we dug into.

Get-SPWeb Cannot access the local farm

Get-SPWeb : Cannot access the local farm. Verify that the local farm is properly configured, currently available, an
d that you have the appropriate permissions to access the database before trying again.

I was using one of the farm service accounts to run my PowerShell scripts, not good.
The service account was locked and caused the above error.