Powershell Learning Area

My Goal: To build a SP Farm with all Service Apps and functionality installed via PowerShell one command at a time in an attempt to learn PowerShell for SharePoint. Then to manipulate list configuration and data etc.

Getting Started with PowerShell for SharePoint from Hey Scripting Guy

First install the PowerShell ISE (Integrated Scripting Environment). It is a Windows Feature. Or install using Powershell command     Import-Module Servermanager; Add-WindowsFeature "PowerShell-ISE"   This will allow you to develop scripts, functions etc. in a similar fashion to how I do it in SQL Query Windows. The SP bits must be installed to allow you to add the snap in per next step (not a farm)

To run commands in PS ISE, you need to add SP Snap in and run in same thread

$ver = $host | select version
if ($ver.Version.Major -gt 1) {$Host.Runspace.ThreadOptions = "ReuseThread"}
Add-PsSnapin Microsoft.SharePoint.PowerShell
Set-location $home

By default, the Execution Policy is set to Restricted

If you are running the Management Shell on a SharePoint server, it is likely that the output from Get-ExecutionPolicy command is Restricted.

When not in Production set to unrestricted like this:   Set-ExecutionPolicy Unrestricted

Restricted: Individual cmdlets can be run, but not saved.

AllSigned: Scripts can run, but must have a digital signature even if written on the local computer. Prompts you before running scripts from trusted publishers.

RemoteSigned: Scripts written on the local computer do not need a digital signature, but any script downloaded from outside (email, IM, Internet) must have a signature to execute. To sign scripts, use the Set-AuthenticodeSignature cmdlet, which can be used to add an Authenticode signature to a Windows PowerShell script or other file.

Unrestricted: Any script can run, but scripts downloaded from outside will run with a warning.

Parameters and different types

param(
[string] $optionalparam1, #an optional parameter with no default value
[string] $optionalparam2 = "default", #an optional parameter with a default value
[string] $requiredparam = $(throw ""requiredparam required."), #throw exception if no value provided
[string] $user = $(Read-Host -prompt "User"), #prompt user for value if none provided
[switch] $switchparam; #an optional "switch parameter" (ie, a flag)
)

2 more examples
param ([System.String] $siteurl = $(throw "Required siteurl parameter is missing!"))
$siteurl = http://sp12

Create Web Apps and Sites Hey Scripting Guy

For help enter: help New-SPWebApplication –examples

$Name = "From PowerShell"
$HH = "SP7.nwi.local"
$URL = ("http://" + $HH)
$AppPool = "SPAppPool"

New-SPWebApplication -Name $Name -ApplicationPoolAccount (Get-SPManagedAccount "NSA\NSAFarmAdmin") -Port 80 -HostHeader $HH –URL $URL -ApplicationPool $AppPool

 

Add a Content Db

New-SPContentDatabase –Name WSS_Content_Powershell –WebApplication “http://SP7.NSA.local”

Now Create Site Collection

$SiteURL = "http://sp7.sp.local"

#$OwnerAlias "NSA\NSAAdmin"

#$SecOwnerAlias "NSA\NSAAdmin"

$database = "SPContent_FromPS"

$SiteCollectionName = "Jim site coll from ps"

$Template = "STS#0"

$LCID = 1033

New-SPSite -Url $SiteURL -OwnerAlias NSA\NSAAdmin -SecondaryOwnerAlias NSA\NSAAdmin -ContentDatabase $database -Description $SiteCollectionName -Name $SiteCollectionName -Language $LCID -Template $Template -ErrorAction Stop

Now run Get some commands

Get-Command cmdlet returns basic information about cmdlets

PS > Get-Command -Noun SPSite

PS > Get-SPSite -Identity http://SPServer | Select-Object -Property Url, Zone, Port

change specific properties of a site collection

PS > Get-SPSite -Identity http://SPServer
>> Set-SPSite -SecondaryOwnerAlias domain\user

PS > Get-SPSite -Identity http://SPServer | Select SecondaryContact

 

Store an object in a variable and set property

PS > $spSite = Get-SPSite -Identity http://SPServer

PS > $spSite.SecondaryContact = 
>> (Get-SPUser -Web http://SPServer -Identity domain\user)

 

Add a user that exists in Active Directory but does not exist in the site collection

Simply use the   New-SPUser cmdlet.

You can also store an object of the type SPSite in a variable and set the SecondaryContact property. The property requires an object of the type Microsoft.SharePoint. SPUser, which is just the type of object that the Get-SPUser cmdlet returns. Note that the user has to exist in the site collection:

PS > $spSite = Get-SPSite -Identity http://SPServer

PS > $spSite.SecondaryContact = 
>> (Get-SPUser -Web http://SPServer -Identity domain\user)

What if you want to add a user that exists in Active Directory but does not exist in the site collection? Simply use the New-SPUser cmdlet to add a user to a site collection and then add the object to the SecondaryContact property:

PS > $spUser = New-SPUser -Web http://SPServer -UserAlias domain\new user

PS > $spSite.SecondaryContact = $spUser

When we are done with the object stored in the $spSite variable, it’s important to dispose of it correctly. One way of doing this is by calling the Dispose() method:

PS > $spSite.Dispose()

 

Tips and Tricks

No 1 – concatenation of parameter

$SiteCollectionURL = ("http://" + $WebAppHostHeader)

No 2 from here How to call a script from PowerShell console

Easy way: change the directory location in console to where the script is stored ie c:\runscripts. the execute like this .\thescript.ps1 ParametergoesHereWithNoQuotes

when the script file path contains white space? because executing this:

PS C:\> c:\new folder\myscript.ps1 param1

will give this error:

The term ‘c:\new’ is not recognized as a cmdlet, function, operable program, or script file. Verify the term and try again.

Putting the path between quotations like this:

PS C:\> "c:\new folder\myscript.ps1" param1

Will lead to:

Unexpected token ‘param1’ in expression or statement.

The solution is to use the Invoke Operator "&", which is used to run script blocks

PS C:\> & 'c:\new folder\myscript.ps1' param1

Now coming to the next part which is calling this from command line.  Executing a PowerShell script from command line is as easy as:

C:\Documents and Settings\Hesham>powershell c:\MyScript.ps1 param1

This is fine as long as the script path has no spaces. For example, executing:

C:\Documents and Settings\Hesham>powershell c:\new folder\MyScript.ps1 param1

Again gives:

The term ‘c:\new’ is not recognized as a cmdlet, function, operable program, or script file. Verify the term and try again.

With the help of PowerShell -?, here is a solution:

C:\Documents and Settings\Hesham>

powershell -command "& {&'c:\new folder\MyScript.ps1' param1}"

Tip no 3 Command interface tricks

Buffered commands can be displayed in order numerically from a pop-up window by pressing F7, scroll up and down and  then enter number of the buffered item to re-run it. or The buffered commands can be displayed from the command line by typing the first few characters of the command you want and then pressing F8.

To copy and paste text, right-click the command-line interface title, click Mark, highlight the text you want to copy, and then right-click the window title again to copy the selected text automatically into the Clipboard.

You can execute many commands on the same line. In Windows PowerShell, you separate commands using the semicolon character (;).

Tip No 4 Sending Output text

Output from a command can be directed to a file named to the right of >. This will overwrite the file if it already exists. To redirect the output but append it to the file, use >>. Error messages that result from running a command can be redirected to a file named to the right of 2>, or they can be appended to a file by using 2>> or sent to the same destination as the standard output by using 2>&1.

Tip No 5 – Aliases and shortcuts

Aliases and shortcuts can be substituted for commonly used commands. For example, the ForEach-Object cmdlet can be replaced with ForEach or even with the percentage character, %. The question mark character, ?, can be used in place of Where or Where-Object. You can also use Get-Alias to return a list of aliases. Note that the use of aliases in scripts can make them difficult to understand.

Tip No 6 Using Scripts in Org with Multiple Environments. from here

In an organization that has multiple environments, such as development, system integration, user acceptance test (UAT), pre-production, and production, consider the need to sign code on your production and UAT farms at minimum. You should also review the execution policy settings for these farms. You can set the execution policy in a Group Policy Object that targets either users or computers so that it cannot be overridden when someone logs on to your SharePoint servers.

For more information on Windows PowerShell execution policies and signing scripts, see the TechNet article "Heading Off Malicious Code" at http://technet.microsoft.com/en-us/magazine/2008.01.powershell.aspx, or type Get-Help about_Execution_Policies at a Windows PowerShell command-line interface. There is also a blog post that explains the process in detail. It is "ALLSigned: Signing Your PowerShell Scripts" and can be found at http://sharepoint.microsoft.com/blogs/zach/Lists/Posts/Post.aspx?ID=53.

 

stuff from ilove SharePoint guy Christian Glessner

  • >$web = get-spweb http://localhost
  • >$web.Title = "Greetings from the Powershell"
  • >$web.Update()

SharePoint and PowerShell are a perfect match. Here’s the PowerShell profile I’m using on my Sharepoint Dev. Boxes.

If you haven’t a PowerShell profile yet, create it:

  • >new-item -type file $profile -force
  • >notepad $profile
  • Paste in the following snippet or download:
$12HivesDir = "${env:CommonProgramFiles}\Microsoft Shared\web server extensions\12\"
 
#load Microsoft.SharePoint.dll
[System.Reflection.Assembly]::LoadFrom("$12HivesDir\ISAPI\Microsoft.SharePoint.dll")
 
#returns the SPSite at the specified URL
function get-spsite ([String]$webUrl=$(throw 'Parameter -webUrl is missing!'))
{
   return New-Object -TypeName "Microsoft.SharePoint.SPSite" -ArgumentList "$webUrl";
}
 
#returns the SPSite object from the specified URL
function get-spweb ([String]$webUrl=$(throw 'Parameter -webUrl is missing!'))
{
   $site =  New-Object -TypeName "Microsoft.SharePoint.SPSite" -ArgumentList "$webUrl";
   return $site.OpenWeb();
}
 
#returns the SPList object from the specified URL and List name
function get-splist ([String]$webUrl=$(throw 'Parameter -webUrl is missing!'),
[String]$listName=$(throw 'Parameter -listName is missing!'))
{
   $site =  New-Object -TypeName "Microsoft.SharePoint.SPSite" -ArgumentList "$webUrl";
   $web = $site.OpenWeb();
   return $web.Lists[$listName]
}
 
  • Save
  • >set-executionpolicy -executionPolicy remoteSigned
  • Reopen the PowerShell 
      Advertisements