Tuesday 3 November 2015

Basic Windows Powershell for Sharepoint


Ensure before the SharePoint PowerShell snapin is loaded or not
When using the “SharePoint 2013 Management Shell” (the ugly black one) it automatically loads a “snapin” which is basically a PowerShell extension that gives you a series of commands for working with SharePoint objects. When you use the Windows PowerShell ISE it has no idea of SharePoint, so you need to load the SharePoint snapin manually. The simplest way to do this is just to add the following code snippet to the start of all your scripts.

if((Get-PSSnapin "Microsoft.SharePoint.PowerShell") -eq $null)
{
      Add-PSSnapin Microsoft.SharePoint.PowerShell
}

 This will get you an object of the Site Collection at that URL and put it in the variable $site. From here you can use some very important CMDLET tools such as Get-Member or Get-Help to figure out the next logical path. Get-Member is used to get any methods and properties of your newly acquired object, and is used in the format:
$site | Get-Member
This will output a list of methods and properties that can then be accessed using dot notation, such as$site.webs to show a list of sub-webs in the site Collection.

So now we have some idea of where we want to start, and how to dig a little deeper to find the relevant data, but what do we do with the data once we find it? When I am working with large sets of relational data I like to use XML. I might use this if I am making a blueprint of web applications, their configuration objects, databases, site collections, etc. For day to day quick scripting I prefer CSV. It is a very portable format that is great for storing row-like sets of data, and it can be opened in Excel for quick editing before putting back into SharePoint.

Below is an example of how you can quickly create a CSV file using PowerShell:
# This creates an empty array. This will be used to create an array of rows to be written to the CSV file
$CSV = @() 

# $newRecord is an empty object that we are creating with the columns First, Last, SSN, and DOB. 
$newRecord = "" | select First, Last, SSN, DOB

# Now that we have the empty object, we are going to use dot notation to add data to each column of the record
$newRecord.First = "Corey"
$newRecord.Last = "Burke"
$newRecord.SSN = "555-55-5555"
$newRecord.DOB = "5/17/2905" #I’m from the future. I come in peace…

# Now that the record is populated, we need to add it to the $CSV array.
$CSV += $newRecord

# Once we are finished populating the $CSV array with records, we need to write the array to a .csv file using the Export-CSV CMDLET
$CSV | Export-CSV “PersonalInfo.csv” –NoTypeInformation
The above code should generate a CSV file with the column headers and one populated row. More records can be added by using a loop to create a new $newRecord after the last one has been written to the $CSV array.

“That’s great!” you say, “but what do I do with the CSV? It’s just a bunch of text in a file.”