Sunday, July 08, 2018

ADD MICROSOFT.SHAREPOINT.POWERSHELL SNAP-IN TO ALL POWERSHELL WINDOWS

Problem Statement:

 Whenever I wrote Sharepoint reIated powershell script I had to constantly add the line Add-PSSnapin 
"Microsoft.SharePoint.PowerShell" at the top of every script I wrote, and I wanted it to just already be there like it is when I run the SharePoint Management Shell. 

Solution:


Add the snap-in code to the PowerShell profile.
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.  If you simply execute $profile.AllUsersAllHosts, you will see the path where this file is stored (be default it is C:\Windows\System32\WindowsPowerShell\v1.0).

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.  It will take a little longer than usual to open the window because it is executing the code from Profile.ps1 and adding the Microsoft.SharePoint.PowerShell snap-in.  To test it, run a command such as Get-SPFarm.

No comments: