0

I want to know what is the best way to load Microsoft.SharePoint.PowerShell assembly in Powershell IDE.

Because I looked many variations on the internet(ect. google).

First option:

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

Second option:

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
Add-PSSnapin "Microsoft.SharePoint.PowerShell"

Best option is?

1

First option is best way to load the power-shell libraries. as second option was in SharePoint 2007 but after SharePoint 2010 Microsoft introduce the snap-ins which reduces the number of lines to load the power-shell assemblies.

you can find more info here

| improve this answer | |
1

The best way to do this in SharePoint 2010 and above is:

Add-PSSnapin Microsoft.SharePoint.PowerShell -EA 0

This will ignore errors if the snaphin is already loaded.

| improve this answer | |
1

Another method is add it to your profile. Follow these steps

  • Open up PowerShell ISE and run the following to create a profile script if one doesn’t exist and edit it in the ISE:
if (!(test-path $profile.AllUsersAllHosts)) {new-item -type file -path $profile.AllUsersAllHosts –force}

powershell_ise $profile.AllUsersAllHosts
  • That will open a new tab in PowerShell ISE allowing you to edit profile.ps1

  • In PowerShell ISE, you will now have a new tab where you can edit this file. In that new tab, add the following code and then save the file.

    $ver = $host | select version

     if ($ver.Version.Major -gt 1) {$host.Runspace.ThreadOptions = "ReuseThread"} 
    
     if ((Get-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue) -eq $null) 
    
     {
    
         Add-PSSnapin "Microsoft.SharePoint.PowerShell"
    
     }
    
  • Now, close PowerShell ISE and then open it again.

Please read complete details here: Add Microsoft.SharePoint.PowerShell Snap-In to All PowerShell Windows

| improve this answer | |
0

For the two options you specified, both would work. But I will choose the first one, because it will first check if the Microsoft.SharePoint.PowerShell has been loaded, if not then use Add-PSSnapin command to add, it is more suitable with logic side and better.

| improve this answer | |
0

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction "SilentlyContinue"

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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