onsdag den 20. februar 2013

Adding SharePoint PowerShell snapins


Over time I have seen a lot of ways to add the SharePoint snapins. So I decided that I would share my point of view on this.

So a lot of post on the internet is showing various ways to do this, by as the structure fascist I am, I like to keep things organized. So I always put my code in functions.

Why?

Well first it gives you a nice overview of the code, Always put your main code in a main function. This way it’s always on the top of your script. Second. By adding all your code in functions you can call the reuse then over and over again in your script.

It’s also a good idea to let your script tell you where in the process it is. This gives you a nice overview over watt you script is doing

So how do I add the snapin.

function snapin
{
  $spSnapin = Get-PSSnapin | where {$_.Name -eq "Microsoft.SharePoint.PowerShell"}        
  if($spSnapin -eq $null)
  {
    Add-PSSnapin Microsoft.SharePoint.PowerShell
    Write-Host -ForegroundColor "Green" -Object "SharePoint PowerShell Snapin loaded"
  }
  else        
  {  
     Write-Host -ForegroundColor "Gray" -Object "SharePoint PowerShell Snapin already loaded"
  }
}
  
So after adding this function I call this function just before I call the main function. My structure will always look like this.

function
main
function snapin

snapin
main
# end of script

Ingen kommentarer:

Send en kommentar