Auto Load SharePoint Snap In and other modules and code when launching PowerShell

Posted: August 26, 2014 in PowerShell scripts, SharePoint PowerShell

When being an active PowerShell user it can be handy to have your favourite modules and Snapin’s available on PowerShell Launch!
Every user on the server will have his/her own “location” ps1 file that probably does not exist at the moment. You will probably have to create it first.

To test, type inn $profile in Powershell. It will return a path to your profile ps1 file. To see if it exists type in:

test-path $profile

If it doesn’t exist, we will have to create it:

If the profile ps1, does not exist, create it and and the Sharepoint snap-in:

if (!(Test-Path $profile))
    {
    New-Item -path $profile -type file -force | Out-Null
    }

To add a snap-in:

If it exists and already contains other code, you can for example add the SharePoint snap-in with:

    if (Test-Path $profile)
    {
    add-Content $profile 'Add-PSSnapin microsoft.sharepoint.powershell -EA "SilentlyContinue"'
    }

You can also for example add the option that your PowerShell sessions always starts in administrator mode by adding the text:

$RunAsAdmin = 
{
    If (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))

    {   
    $arguments = "& '" + $myinvocation.mycommand.definition + "'"
    Start-Process powershell -Verb runAs -ArgumentList $arguments
    Break
    }
}



if (Test-Path $profile)
{
add-Content $profile $RunAsAdmin
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s