Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

If I wanted to create a PowerShell script how can I make one that include the sharepoint commandlets

share|improve this question

3 Answers 3

If you launch PowerShell from Start > Microsoft SharePoint 2010 Products > SharePoint 2010 Management Shell, you do not have to register the snap-in that contains the cmdlets. Registration of the Microsoft.SharePoint.PowerShell.dll module for SharePoint 2010 cmdlets is automatic.

However, if you use the Windows PowerShell console, you will need this line:

Add-PSSnapin -Name Microsoft.SharePoint.Powershell -ErrorAction SilentlyContinue

EDIT: The -ErrorAction parameter will keep it from erroring out if the snap-in was already added. This will also mask any error in loading. So, a better alternative might be:

if ((Get-PSSnapin -Name Microsoft.SharePoint.Powershell -ErrorAction SilentlyContinue) -eq $null)
{
    Add-PSSnapin Microsoft.SharePoint.Powershell 
}
share|improve this answer
1  
That will throw an error if script is already loaded. I favor adding -ErrorAction ScilentlyContinue (-EA 0 in short hand) to make it swallow any errors –  Anders Rask May 16 '11 at 22:34
    
Thanks, I'll edit the code to include -ErrorAction parameter. –  Laurie May 16 '11 at 23:03

You should just be able to write your script and save it as a ps1 file.

Once you have done that open the Management Shell and execute it like so:

. 'LocalPath\ScriptName.PS1'

As long as you execute the script from the Management Shell you should have access to all the commandlets.

share|improve this answer

The information in Laurie's post is correct in that you don't have to reference anything if you use the SharePoint Management Shell.

Also, it's often more convenient to add the directory containing your PowerShell scripts to the environment paths variable so that you don't have to browse to the directory to execute them.

You can either add it to the path via settings, or you can put the following in your PowerShell profile and it will execute automatically anytime you open PowerShell.

$env:path = $env:path + ";c:\scripts;"
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.