Skip to content

Instantly share code, notes, and snippets.

@goyuix
Created September 7, 2016 15:08
Show Gist options
  • Save goyuix/c46bed5165aa6e6a9cb0f778068e9ebb to your computer and use it in GitHub Desktop.
Save goyuix/c46bed5165aa6e6a9cb0f778068e9ebb to your computer and use it in GitHub Desktop.
These are first few lines I add to all my SharePoint on-premises scripts. It makes sure that the script is running with admin privileges and loads the Microsoft.SharePoint.PowerShell module. If there are any issue it aborts the script. It pulls some inspiration from the SharePoint Management Shell initialization script sharepoint.ps1.
function Get-AdminStatus {
$identity = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$principal = New-Object System.Security.Principal.WindowsPrincipal $identity
$principal.IsInRole
$status = $principal.IsInRole("Administrators")
$principal = $null
$identity.Dispose()
return $status
}
if (Get-AdminStatus -eq $false) {
Write-Host "Aborting script - SharePoint requires running with administrator privileges"
return
}
$Host.Runspace.ThreadOptions = "ReuseThread"
Add-PsSnapin Microsoft.SharePoint.PowerShell -ErrorAction 0
if ((Get-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction 0) -eq $null) {
Write-Host "Aborting script - SharePoint PowerShell module does not appear to be loaded"
return
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment