ASP.NET, SharePoint

Facilitating Sharepoint using powershell commands

Purpose

There are many things in sharepoint that is not possible or require alot of manually work. Powershell helps us to do these tasks sail through . There are n number of things in which powershell help us in sharepoint. Some of them are discussed below :

Get all the permission group and user in that from sharepoint site

This command helps you to get all the groups in the sharepoint site and also let you know about the permission levels of the corresponding people of each group. Also these records are generated in the form of csv file that can be exported.

[System.Reflection.Assembly]::LoadWithPartialName(“Microsoft.SharePoint”) > $null
$farm = [Microsoft.SharePoint.Administration.SPFarm]::Local
$websvcs = $farm.Services | where -FilterScript {$_.GetType() -eq [Microsoft.SharePoint.Administration.SPWebService]}
#Output Report File
$outputReport = “C:\test.txt”
#Write Output Report CSV File Headers
“WebApplicationName, SiteName, WebName, GroupName, UserName” | out-file $outputReport
$webapps = @()

foreach ($websvc in $websvcs) {
foreach ($webapp in $websvc.WebApplications) {
Write-host “Scanning Web Application Policies…”
foreach ($site in $webapp.Sites) {
Write-host “Scanning Web Application…” $webapp.Name
foreach ($web in $site.AllWebs) {
Write-host “Scanning Web App…” $site.URL

foreach ($group in $web.Groups) {
foreach ($user in $group.Users) {
“$($webapp.Name),$($site.URL), $($web.URL), $($group.Name), $($user.Name)” | Out-File $outputReport -Append
}
}
}
}
}
}

write-host “Fetched all the groups and user inside that groups ”

Remove In-active user’s from Sharepoint site

This command first of all checks for all the inactive users in AD and then after getting the inactive user’s , it will remove all the inactive users in sharepoint site and site collections.

#Powershell to Remove Orphaned Users from SharePoint 2013/2010
#Modified Powershell Code from http://www.sharepointdiary.com/2013/07/find-and-delete-orphaned-users-in-sharepoint-using-powershell.html

#Load SharePoint Management shell
if ((Get-PSSnapin “Microsoft.SharePoint.PowerShell” -ErrorAction SilentlyContinue) -eq $null) {
Add-PSSnapin “Microsoft.SharePoint.PowerShell”
}
#Function to Check if an User exists in AD
function CheckUserExistsInAD()
{
Param( [Parameter(Mandatory=$true)] [string]$UserLoginID )
#Search the User in AD
$forest = [System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest()
foreach ($Domain in $forest.Domains)
{
$context = new-object System.DirectoryServices.ActiveDirectory.DirectoryContext(“Domain”, $Domain.Name)
$domain = [System.DirectoryServices.ActiveDirectory.Domain]::GetDomain($context)

$root = $domain.GetDirectoryEntry()
$search = [System.DirectoryServices.DirectorySearcher]$root
$search.Filter = “(&(objectCategory=User)(samAccountName=$UserLoginID))”
$result = $search.FindOne()

if ($result -ne $null)
{
return $true
}
}
return $false
}
#Change these variables as desired
$WebAppURL=”http://tech-sr-38″
$RemoveUsers = $false

#Get all Site Collections of the web application
$WebApp = Get-SPWebApplication $WebAppURL
$textout = “”
$textout > “.\SharePointOrphanedUsers.csv”
#Iterate through all Site Collections
foreach($site in $WebApp.Sites)
{
if ($site -ne $null)
{
$web = $site.AllWebs
foreach ($webp in $web)
{
Write-Host $webp.URL
if($webp.URL)
{
$OrphanedUsers = @()
if (($webp.permissions -ne $null) -and ($webp.hasuniqueroleassignments -eq “True”))
{
#Iterate through the users collection
foreach($User in $webp.SiteUsers)
{
#Exclude Built-in User Accounts , Security Groups & an external domain “corporate”
if(($User.LoginName.ToLower() -ne “nt authority\authenticated users”) -and
($User.LoginName.ToLower() -ne “nt authority\system”) -and
($User.LoginName.ToLower() -ne “sharepoint\system”) -and
($User.LoginName.ToLower() -ne “nt authority\local service”) -and
($user.IsDomainGroup -eq $false ) -and
($User.LoginName.ToLower().StartsWith(“corporate”) -ne $true) )
{
$UserName = $User.LoginName.split(“\”) #Domain\UserName
$AccountName = $UserName[1] #UserName

#If the user does not exist in Active Directory then it is an orphaned account in the SharePoint Site Collection
if ( ( CheckUserExistsInAD $AccountName) -eq $false )
{
$textout = “””$($User.Name)””,””$AccountName””,””($($User.LoginName))””,””$($webp.URL)”””
#Write-Host $textout
$textout >> “.\SharePointOrphanedUsers.csv”
#Make a note of the Orphaned user
$OrphanedUsers+=$User.LoginName
}
}
}
# **** Remove Users ****#
# Remove the Orphaned Users from the site
if ($RemoveUsers)
{
foreach($OrpUser in $OrphanedUsers)
{
$webp.SiteUsers.Remove($OrpUser)
Write-host “Removed the Orphaned user $($OrpUser) from $($webp.URL) ”
}}}}}}}

Apply Master page to multiple site collections

In Some cases, you have n number of site’s in sharepoint and if you need to update the master page for all the sites, that will be a time consuming task. Powershell provide us feature to update all the master page at once. Below is the command for the same

$site = Get-SPSite http://localhost/
foreach ($web in $site.AllWebs)
{
#$web.MasterUrl = $site.RootWeb.ServerRelativeUrl + “/_catalogs/masterpage/seattle.master”;
#$web.CustomMasterUrl = $site.RootWeb.ServerRelativeUrl + “/_catalogs/masterpage/seattle.master”;
#$web.Update();
Write-Host $web.Url $web.MasterUrl $web.CustomMasterUrl;
}

Deploy code to multiple folder structure.

In some cases, you need to deploy your code to multiple folder structure. Again that will be a mind boggling job. At that time instead of manually copying code you can use this powershell command.

Install-SPSolution -Identity <wsp name> -WebApplication “<Web application Name>” -GACDeployment -CompatibilityLevel {14,15}

Copy sharepoint List item to other list item

Sometimes, when you need to copy one list column to other column, role of this command comes into play. Consider a scenario where you are using one field as lookup and later you need to change the type of column, but if you did so all the data in that column will be lost. In such cases, you can create a new column with the required data type and copy the previous column to the new one.

Add-PSSnapin Microsoft.Sharepoint.Powershell
[System.reflection.Assembly]::LoadWithPartialName(“Microsoft.SharePoint”)
$site = new-object Microsoft.SharePoint.SPSite(“SiteURL”)
$web = Get-SPWeb -Identity siteURL
$lista =$web.Lists[“ListName”]
$items = $lista.items
foreach ($item in $items) {
$user = $item[“A”]
$item[“B”] = $user
write-host $user
$item.update()
}
$lista.update()

About The Author

Leave a Reply

*