Blog Image

PowerShell

SharePoint Powershell Commands

GoSharePoint Website
Documentation Blog

This blog is based on SharePoint 2013 PowerShell Commands. Please visit my other blog which contains SharePoint Documentation.

Connect to an existing Server Farm

Installation Posted on Mon, June 27, 2016 19:08:41

<#====================================================================

Copyright © 2015, June. Michael Pomfret

Connect to an existing Server Farm

You should replace the “<Server name>” with the correct windows server name.

You should replace the “<SharePoint Configuration DB>” with the correct SharePoint Configuration database name.

You should replace the “<YourPassPhase>” with the correct passphase.

====================================================================#>

cls

Write-Host “SharePoint 2013 – Connect to an existing Server Farm…”

$DBServer = ‘<Server name>’

$ConfigDB = ‘<SharePoint Configuration DB>’

$PassPhrase = ‘<YourPassPhase>’

$SecPassPhrase = ConvertTo-SecureString $PassPhrase –AsPlaintext –Force

Write-Host ” – Enabling SP PowerShell cmdlets…”

If ((Get-PsSnapin |?{$_.Name -eq “Microsoft.SharePoint.PowerShell”})-eq $null)

{

Add-PsSnapin Microsoft.SharePoint.PowerShell | Out-Null

}

Start-SPAssignment -Global | Out-Null

Write-Host ” – Connecting to server farm…”

Connect-SPConfigurationDatabase -DatabaseServer $DBServer -DatabaseName $ConfigDB -Passphrase $SecPassPhrase

Write-Host ” – Installing Help Collection…”

Install-SPHelpCollection -All

Write-Host ” – Securing Resources…”

Initialize-SPResourceSecurity

Write-Host ” – Installing Services…”

Install-SPService

Write-Host ” – Installing Features…”

$Features = Install-SPFeature –AllExistingFeatures -Force

Write-Host ” – Installing Application Content…”

Install-SPApplicationContent

Stop-SPAssignment -Global | Out-Null



Configure People Picker for cross-forest or cross-domain queries when you use a one-way trust

Installation Posted on Mon, June 27, 2016 18:56:28

<#====================================================================

Copyright © 2016, June. Michael Pomfret

Configure People Picker for cross-forest or cross-domain queries when you use a one-way trust

You should replace the “xxxxxx” with the correct passwords for the user.

Check and amend correct AD domain .

https://technet.microsoft.com/en-us/library/gg602075.aspx?f=255&MSPPError=-2147217396

====================================================================#>

Set-ExecutionPolicy -ExecutionPolicy “Unrestricted” -Force

Add-PSSnapin “Microsoft.SharePoint.PowerShell”

stsadm -o setapppassword -password xxxxxxx

STSADM -o setproperty -pn peoplepicker-searchadforests -pv “domain:yourdomain.com,AD\pBI_SP_Profile,8Pgk59sKH;forest:ad.domain.com,AD\xxx_SP_Profile,xxxxxxxxx” -url http://SharePoint_Site

STSADM -o setproperty -pn peoplepicker-searchadforests -pv “domain:yourdomain.com,AD\pBI_SP_Profile,8Pgk59sKH;forest:ad.domain.com,AD\xxx_SP_Profile,xxxxxxxxx” -url http://central_admin:port



Get the SharePoint variables from a text file

Installation Posted on Mon, June 27, 2016 18:47:55

<#====================================================================

Copyright © 2015, September. Michael Pomfret

Get the SharePoint variables from a text file

====================================================================#>

if ($AppPoolAcc -eq $null){

Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Scope CurrentUser

# PowerShell script to get common Varaible from a file

$Data = “C:\temp\SP_Variables.txt”

$lines = Get-Content $Data | Where {$_.trim() -ne “” -and $_ -notmatch ‘#’}

foreach ($line in $lines) {

$variablename = $line -split ‘=’

if (!$variablename)

{ New-Variable -Name variablename[0] -Value $Global:variablename[1]}

else

{

set-Variable -Name $variablename[0] -Value $variablename[1]

}

}

}else

{

write “variables ok”

}



Create a new Server Farm

Installation Posted on Mon, June 27, 2016 18:46:25

<#====================================================================

Copyright © 2015, September. Michael Pomfret

Creating a new Server Farm

The script only targets the server you are running the script on

and does the following:

-Creates the SharePoint Configuration content database.

-Creates the SharePoint Administration content database.

-Install SharePoint services

-Install SharePoint features

-Copies shared application data to existing Web application folders.

====================================================================#>

Write-Host “- Enabling SP PowerShell cmdlets…”

If ((Get-PsSnapin |?{$_.Name -eq “Microsoft.SharePoint.PowerShell”})-eq $null)

{

Add-PsSnapin Microsoft.SharePoint.PowerShell | Out-Null

}

Write-Host “SharePoint 2013 – Creating a new Server Farm…”

$SecPassPhrase = ConvertTo-SecureString $PassPhrase –AsPlaintext –Force

$FarmAccPWD = ConvertTo-SecureString $FarmPassword –AsPlaintext –Force

$cred_FarmAcc = New-Object System.Management.Automation.PsCredential $FarmAcc,$FarmAccPWD

Start-SPAssignment -Global | Out-Null

Write-Host “====================================================================”

Write-Host “- Creating configuration database…”

Write-Host “- Using DBServer…”$DBServer

Write-Host “- Using Central Admin Content DB…”$CentralAdminContentDB

Write-Host “- Using Port…”$CentralAdminPort

Write-Host “====================================================================”

Write-Host

New-SPConfigurationDatabase –DatabaseName “$ConfigDB” –DatabaseServer “$DBServer” –AdministrationContentDatabaseName “$CentralAdminContentDB” –Passphrase $SecPassPhrase –FarmCredentials $cred_FarmAcc

Write-Host “- Installing Help Collection…”

Install-SPHelpCollection -All

Write-Host “- Securing Resources…”

Initialize-SPResourceSecurity

Write-Host “- Installing Services…”

Install-SPService

Write-Host “- Installing Features…”

$Features = Install-SPFeature –AllExistingFeatures -Force

Write-Host “- Creating Central Admin…”

$NewCentralAdmin = New-SPCentralAdministration -Port $CentralAdminPort -WindowsAuthProvider “NTLM”

Write-Host “- Waiting for Central Admin to provision…”-NoNewline

Write-Host ” Created!”

Write-Host “- Installing Application Content…”

Install-SPApplicationContent

Stop-SPAssignment -Global | Out-Null



Adds SharePoint Administrators to the local administrator Group

Windows Server Posted on Mon, June 27, 2016 17:38:28

<#====================================================================

Copyright © 2015, September. Michael Pomfret

Adds a number of SharePoint Administrators to the local administrator Group

1. Function to check for the existence of Local group.

2. function to create the local group

====================================================================#>

# Powershell function to check for the Local user account…

function LocalUserExist($userName)

{

$Computer = [ADSI]”WinNT://$Env:COMPUTERNAME,Computer”

# Local user account creation:

$colUsers = ($Computer.psbase.children | Where-Object {$_.psBase.schemaClassName -eq “User”} | Select-Object -expand Name)

$userFound = $colUsers -contains $userName

return $userFound

}

# Powershell to check for the existence of Local group…

function LocalGroupExist($groupName)

{

return [ADSI]::Exists(“WinNT://$Env:COMPUTERNAME/$groupName,group”)

}

# Powershell function to create the local user…

function CreateLocalUser($userName,$password)

{

$userExist = LocalUserExist($userName)

if($userExist -eq $false)

{

$User = $Computer.Create(“User”, $userName)

$User.SetPassword($password)

$User.SetInfo()

$User.FullName = “Full Name”

$User.SetInfo()

$User.UserFlags = 64 + 65536 # ADS_UF_PASSWD_CANT_CHANGE + ADS_UF_DONT_EXPIRE_PASSWD

$User.SetInfo()

}

else {

“User : $userName already exist.”

}

}

# PS function to create the local group

function CreateLocalGroup($groupName)

{

$groupExist = LocalGroupExist($groupName)

if($groupExist -eq $false)

{

$Group = $Computer.Create(“Group”, $groupName)

$Group.SetInfo()

$Group.Description = $groupName

$Group.SetInfo()

}

else

{

“Group : $groupName already exist.”

}

}

# PS function to check for the group in the local machine…

function CheckGroupMember($groupName,$memberName)

{

$group = [ADSI]”WinNT://$Env:COMPUTERNAME/$groupName”

$members = @($group.psbase.Invoke(“Members”))

$memberNames = $members | foreach {$_.GetType().InvokeMember(“Name”, ‘GetProperty’, $null, $_, $null)}

$memberFound = $memberNames -contains $memberName

return $memberFound

}

# PS function to add a user to the group…

function AddUserToGroup ($groupName, $userName)

{

$group = [ADSI]”WinNT://$Env:COMPUTERNAME/$groupName”

$user = [ADSI]”WinNT://$Env:COMPUTERNAME/$userName”

$memberExist = CheckGroupMember $groupName $userName

if($memberExist -eq $false)

{

$group = [ADSI]”WinNT://$Env:COMPUTERNAME/$groupName”

$user = [ADSI]”WinNT://$Env:COMPUTERNAME/$userName”

$group.Add($user.Path)

}

}

Write-Host “Windows Server 2012 – Adding SharePoint Setup Administrator to local administrators group”

$ADusername = “xxx_SP_Farm”

$groupName = “Administrators”

if (CheckGroupMember($groupName,$ADusername)-eq $false)

{

$domain = “AD”

$strComputer = $env:computername

$username = “xxx_SP_Farm”

$computer = [ADSI](“WinNT://” + $strComputer + “,computer”)

$computer.name

$Group = $computer.psbase.children.find(“Administrators”)

$Group.name

$Group.Add(“WinNT://” + $domain + “/” + $username)

}

else

{

“Username : $ADusername already exist.”

}

cmd.exe /c pause



Add Users and Groups on the Local Machine

Windows Server Posted on Mon, June 27, 2016 17:33:00

<#====================================================================

Copyright © 2016, June. Michael Pomfret

Add the active directory Users and Groups on the Local Machine

1. Function to add a user to the group.

2. Function to check for the existence of Local group.

3. Function to check for the Local user account.

4. function to add a user to the group.

5. Function to create the local group.

6. Function to check for the group in the local machine.

7. Function to check for the existence of Local group.

You should replace the “xxxxxx” with the correct passwords for the user.

Check and amend correct AD domain .

====================================================================#>

cls

Set-ExecutionPolicy RemoteSigned

# Powershell function to create the local user…

function CreateLocalUser([string]$userName,[string]$password)

{

write-host -foregroundcolor Red “Checking CreateLocalUser” $userName “password ” $password

write-host “”

write-host “Checking user” $userName

$userExist = LocalUserExist($userName)

if($userExist -eq $false)

{

$User = $Computer.Create(“User”, $userName)

$User.SetPassword($password)

$User.SetInfo()

$User.FullName = $userName

$User.SetInfo()

$User.UserFlags = 64 + 65536 # ADS_UF_PASSWD_CANT_CHANGE + ADS_UF_DONT_EXPIRE_PASSWD

$User.SetInfo()

}

else {

“User : $userName already exist.”

}

}

# Powershell to check for the existence of Local group…

function LocalGroupExist($groupName)

{

return [ADSI]::Exists(“WinNT://$Env:COMPUTERNAME/$groupName,group”)

}

# Powershell function to check for the Local user account…

function LocalUserExist($userName)

{

write-host -foregroundcolor Blue “Checking Local User Exist” $userName

$Computer = [ADSI]”WinNT://$Env:COMPUTERNAME,Computer”

# Local user account creation:

$colUsers = ($Computer.psbase.children | Where-Object {$_.psBase.schemaClassName -eq “User”} | Select-Object -expand Name)

$userFound = $colUsers -contains $user

return $userFound

}

# PS function to add a user to the group…

function AddUserToGroup ($groupName, $userName)

{

$group = [ADSI]”WinNT://$Env:COMPUTERNAME/$groupName”

$user = [ADSI]”WinNT://$domain/$username”

$memberExist = CheckGroupMember $groupName $userName

if($memberExist -eq $false)

{

# Used when user are on local machine – please -ignore

# $group = [ADSI]”WinNT://$Env:COMPUTERNAME/$groupName”

# $user = [ADSI]”WinNT://$domain/$username”

$user = [ADSI]”WinNT://$domain/$userName”

$group = [ADSI]”WinNT://$computerName/$groupName,group”

$group.add(“WinNT://$Domain/$username,group”)

}

}

# PS function to check for the group in the local machine…

function CheckGroupMember($groupName,$memberName)

{

write-host “checking for the group member” $memberName “in the local machine…” $groupName

$group = [ADSI]”WinNT://$Env:COMPUTERNAME/$groupName”

$members = @($group.psbase.Invoke(“Members”))

$memberNames = $members | foreach {$_.GetType().InvokeMember(“Name”, ‘GetProperty’, $null, $_, $null)}

$memberFound = $memberNames -contains $memberName

return $memberFound

}

# PS function to create the local group

function CreateLocalGroup($groupName)

{

$groupExist = LocalGroupExist($groupName)

write-host “$groupExist ” $groupExist

if($groupExist -eq $false)

{

$Group = $Computer.Create(“Group”, $groupName)

$Group.SetInfo()

$Group.Description = $groupName

$Group.SetInfo()

write-host -foregroundcolor Green “$groupName is added to group”

}

else

{

write-host -foregroundcolor Red “Group : $groupName already exist.”

}

}

cls

$server = “localhost”

$computerName = $env:computername

$GroupList= @(“IIS_IUSRS”,”MIISAdmins”,”WSS_ADMIN_WPG”,”WSS_RESTRICTED_WPG_V4″,”WSS_WPG”)

$IIS_IUSRSList= @(“xxx_SP_AppPool”,”xxx_SP_Excel”,”xxx_SP_Farm”,”xxx_SP_MyPool”,”xxx_SP_Profile”,”xxx_SP_Search”,”xxx_SP_Services”,”xxx_SP_Visio”)

$MIISAdminsList= @(“xxx_SP_Farm”,”xxx_SP_Setup”)

$AdministratorsList= @(“xxx_SP_Farm”,”xxx_SP_Setup”)

$WSS_ADMIN_WPGList= @(“xxx_SP_AppPool”,”xxx_SP_Farm”,”xxx_SP_MyPool”,”xxx_SP_Profile”)

$WSS_RESTRICTED_WPG_V4List= @(“xxx_SP_Farm”,”xxx_SP_Setup”)

$WSS_WPGList= @(“xxx_SP_AppPool”,”xxx_SP_C2WTS”,”xxx_SP_Excel”,”xxx_SP_Farm”,”xxx_SP_MyPool”,”xxx_SP_Profile”)

$AdminList= @(“xxx_SP_Farm”,”xxx_SP_Setup”)

$AdminPasswordList= @(“xxxxxx”,”xxxxxx”)

$UserList= @(“xxx_SP_Crawl”,”xxx_SP_AppPool”,”xxx_SP_Search”,”xxx_SP_Services”,”xxx_SP_Profile”,”xxx_SP_C2WTS”,”xxx_SP_Excel”,”xxx_SP_Visio”,”xxx_SP_PerPoint”,”xxx_SP_Reports”,”xxx_SP_MyPool”)

$UserPasswordList= @(“xxxxxx”,”xxxxxx”,”xxxxxx”,”xxxxxx”,”xxxxxx”,”xxxxxx”,”xxxxxx”,”xxxxxx”,”xxxxxx”,”xxxxxx”,”xxxxxx”)

#foreach ($g in $GroupList) {

#write-host “Checking Group” $g “array” (“$” += $g += “List”)

# foreach ($u in ‘$(“$” += $g += “List”)’) {

# write-host “Attempting to add User” $u “To Group” $g

# AddUserToGroup g$ $u

# }

#}

#$Domain = $env:USERDNSDOMAIN

$Domain = “ad.domain.com”

$Computer = [ADSI]”WinNT://$Env:COMPUTERNAME,Computer”

foreach ($grp in $GroupList) {

CreateLocalGroup($grp)

}

foreach ($u in $IIS_IUSRSList) {

write-host “Attempting to add User” $u “ToGroup IIS_IUSRS”

AddUserToGroup “IIS_IUSRS” $u

}

foreach ($u in $MIISAdminsList) {

write-host “Attempting to add User” $u “To Group MIISAdmins”

AddUserToGroup “MIISAdmins” $u

}

foreach ($u in $WSS_ADMIN_WPGList) {

write-host “Attempting to add User” $u “To Group WSS_ADMIN_WPG”

AddUserToGroup “WSS_ADMIN_WPG” $u

}

foreach ($u in $WSS_RESTRICTED_WPG_V4List) {

write-host “Attempting to add User” $u “To Group WSS_RESTRICTED_WPG_V4”

AddUserToGroup “WSS_RESTRICTED_WPG_V4” $u

}

foreach ($u in $WSS_WPGList) {

write-host “Attempting to add User” $u “To Group WSS_WPG”

AddUserToGroup “WSS_WPG” $u

}

$i=0

foreach ($User in $AdminList) {

write-host “Attempting ” $User “Password ” $UserPasswordList[$i]

# CreateLocalUser $User $AdminPasswordList[$i]

$i++

}

$i=0

foreach ($User in $UserList) {

write-host “Attempting ” $User “Password ” $UserPasswordList[$i]

# CreateLocalUser $User $UserPasswordList[$i]

$i++

}

foreach ($u in $AdministratorsList) {

write-host “Attempting to add User” $u “To Group Administrators”

AddUserToGroup “Administrators” $u

}

write-host “End”



Performs a Full or Differential backup of the local computer and emails user on completion

Backup / Restore Posted on Mon, June 27, 2016 17:16:39

<#====================================================================

Copyright © 2016, June. Michael Pomfret

Performs a Full or Differential backup of the local computer and emails user on completion.

1. Script set to complete a full backup on Sunday.

2. Script set to complete a Differential backup on every day excepy Sunday.

====================================================================#>

Set-ExecutionPolicy -ExecutionPolicy “Unrestricted” -Force

Add-PSSnapin “Microsoft.SharePoint.PowerShell”

$ScriptStart = (Get-Date)

$strToday = “Universal Time: ” + $ScriptStart.ToUniversalTime()

$ThisComputer = $env:COMPUTERNAME

$backupDir = “<Drive>:\SharePoint\Backup\” + $ThisComputer

$strToday = (Get-Date).ToString(‘dd-MM-yyyy’)

if((get-date).DayofWeek -eq “Sunday”)

{

$subject = “Task Scheduler: Full Weekly Backup Scheduled for ” + $ThisComputer + ” ” + $strToday

$BackupType = “Full”

Backup-SPFarm -BackupMethod Full -Directory $backupDir

}

else

{

$subject = “Task Scheduler: Daily Backup Scheduled for ” + $ThisComputer + ” ” + $strToday

$BackupType = “Differential”

Backup-SPFarm -BackupMethod Differential -Directory $backupDir

}

$ScriptEnd = (Get-Date)

$RunTime = New-Timespan -Start $ScriptStart -End $ScriptEnd

$smtp = “courier.cf.ac.uk”

$to = “pomfretml@domain.com”

$from = “SharePoint@”+$ThisComputer+”.cf.ac.uk”

$body = “The ” + $BackupType + ” backup has completed for ” + $ThisComputer

$body += ” <br>”

$body += ” <br>”

$body += “Location of Backup ” + $backupDir

$body += ” <br>”

$body += ” <br>”

$body += “Time to complete: {0}:{1}:{2}” -f $RunTime.Hours,$Runtime.Minutes,$RunTime.Seconds

#### Now send the email using > Send-MailMessage

send-MailMessage -SmtpServer $smtp -To $to -From $from -Subject $subject -Body $body -BodyAsHtml -Priority high



Checks whether the script is running as admin

Installation Posted on Mon, June 27, 2016 06:27:42

#***************************************************************************************

# Written by Michael Pomfret

#

# This script checks whether the script is running as admin, if not then starts as admin.

#

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

}

cls

Write-Host -f Cyan “Red ugly warning about set-executionPolicy..”

sleep 2

Write-Host -f Green “OK”

Write-Host “”



Next »