I have written a bunch of PowerShell functions mostly related to SharePoint, but not only SharePoint.
I'd like to extend the SharePoint PowerShell console to make my functions always available from this console.
What is the correct way to extend the console?
By now, I've put all my functions in a custom module. The first line of my module is :
Add-PsSnapin Microsoft.SharePoint.PowerShell -EA 0
This is working as is. If I call Import-Module MyCorp.SP.Powershell, the module is loaded and my method are available. Good.
Now I want to "auto import" this module. I've edited the $profile file to include this line :
Import-Module MyCorp.SP.Powershell
This is working, but when I open the SharePoint console, I get an error :
Add-PSSnapin : Cannot add Windows PowerShell snap-in Microsoft.SharePoint.Powershell because it is already added. Verify the name of the snap-in and try again.
At line:1 char:13
+ Add-PSSnapin <<<< Microsoft.SharePoint.Powershell
+ CategoryInfo : InvalidArgument: (Microsoft.SharePoint.Powershell:String) [Add-PSSnapin], PSArgumentException
+ FullyQualifiedErrorId : AddPSSnapInRead,Microsoft.PowerShell.Commands.AddPSSnapinCommand
This error is not blocking, but annoying. In fact, the SharePoint console (C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\CONFIG\POWERSHELL\Registration\SharePoint.ps1) is adding the snapin, but without checking if it's already loaded.
Can I avoid this message?
I'm not sure modifying the sharepoint.ps1 file is a good idea, because there is a #SIG.
The only workaround I found, is to add this in ALL my functions :
function Ensure-PSSnapin
{
if(-Not(Get-PSSnapin | ? { $_.Name -Eq "Microsoft.SharePoint.PowerShell" })) {
Add-PSSnapin Microsoft.SharePoint.PowerShell
}
}
function Wait-SPSolutionDeploymentJobToFinish
{
param
(
[Parameter(Mandatory=$true)]
[string]$SolutionFileName
)
process {
Ensure-PSSnapin
# actual process removed for readability
}
}
This is quite annoying too, and a source of issues when someone will forget to add this call.
Any advice?