Thursday, October 27, 2016

Copy Permissions from One SharePoint Site to Another using PowerShell

Requirement: Copy permissions from one site to another in SharePoint!

Solution: If you want to copy one SharePoint site to another site, there is no OOTB ways! However, You can use PowerShell to copy permissions between sites. Here is my PowerShell script to copy site permissions.

Copy Permissions from one site to another using PowerShell:
Add-PSSnapin Microsoft.SharePoint.PowerShell -erroraction SilentlyContinue
 
#PowerShell Function to copy permissions from one site to another
Function Copy-SitePermissions()
{
 param(
     $SourceWebURL,
     $TargetWebURL
 )
 Try {
  #Set the Error Action
    $ErrorActionPreference = "Stop"
  
  #Get the Source and Target Webs
  $SourceWeb = Get-SPWeb $SourceWebURL
  $TargetWeb = Get-SPWeb $TargetWebURL
  
  #if permissions are Inherited in the target, Break it!
  if($TargetWeb.Permissions.Inherited)
  {
   #Reset the Inheritence in Target Web
   $TargetWeb.BreakRoleInheritance($false)
  }
   #Copy permissions from Source to Target Web
     $SourceWeb.RoleAssignments | foreach-object {
     $TargetWeb.RoleAssignments.Add($_)
     }
    $TargetWeb.Update()
    Write-Host "Permissions copied from Source Site to the Target!" -f Green
 }
 catch {
   Write-Host $_.Exception.Message -ForegroundColor Red
 }
 finally {
  #Reset the Error Action to Default
  $ErrorActionPreference = "Continue"
 }
}

#Call the function to copy Web permissions 
Copy-SitePermissions -SourceWebURL "http://portal.crescent.com/ProjectHub/" -TargetWebURL "http://portal.crescent.com/TaxAudits/" 


You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Sunday, October 23, 2016

Customize Suitebar Text and Link in SharePoint 2016 using PowerShell

Requirement:
By default, SharePoint 2016 comes with "SharePoint" as the suitebar branding text.  What if you would like to change it to something meaningful, say "Your Company Intranet"? Well, PowerShell can help to customize the branding text, Logo and URL in SharePoint 2016.
sharepoint 2016 add link to suite bar powershell
PowerShell Script to change Suitebar navigation text and link:
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

$WebApp= Get-SPWebApplication "http://intranet.crescent.com"
$WebApp.SuiteNavBrandingText = "Crescent Portal"

#Blank image from Layouts folder
$webapp.SuiteNavBrandingLogoUrl = "/_layouts/images/dot_ruleper.gif"
$webapp.SuiteNavBrandingLogoTitle = "Crescent Logo"
$webapp.SuiteNavBrandingLogoNavigationUrl = "http://portal.crescent.com"
$webapp.Update()

Here is the result of customized SharePoint 2016 suite bar branding using PowerShell!
customizing the sharepoint 2016 suite bar branding using powershell
My another post Customizing the SharePoint 2013 suite bar branding using PowerShell

You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Saturday, October 22, 2016

SharePoint Online: Delete Site Column using Powershell

Requirement: Delete Site Column in SharePoint online using PowerShell

How to delete a site column in SharePoint online?
To remove a SharePoint online site column, follow these steps:
  • Go to Site Settings by clicking Site settings gear and then "Site settings" from the menu.
  • Click on "Site Columns" link from Web Designer Galleries group >> Select the site column to delete.
  • Scroll down and click on "Delete" button and confirm the prompt to delete.
    sharepoint online powershell delete site column
This removes a site column in SharePoint online.

SharePoint online PowerShell to delete site column:
#Load SharePoint CSOM Assemblies
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
  
#Set Variables for Site URL and Site column Title
$SiteURL= "https://crescent.sharepoint.com/sites/sales"
$ColumnName="Sales Region" #Case sensitive

#Setup Credentials to connect
$Cred = Get-Credential
$Cred = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.UserName,$Cred.Password)

Try {
    #Setup the context
    $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
    $Ctx.Credentials = $Cred

    #Check if the site column exists
    $Fields = $Ctx.web.Fields
    $Ctx.Load($Fields)
    $Ctx.ExecuteQuery()
    $FieldNames = $Fields | select -ExpandProperty Title

    #delete site column in sharepoint online
    If($FieldNames.Contains($ColumnName))
    {
        #Delete the site column
        $SiteColumn = $Fields.GetByTitle($ColumnName)
        $Sitecolumn.DeleteObject()
        $Ctx.ExecuteQuery()

        Write-host -f Green "Site Column Deleted Successfully!"
    }
    else
    {
        Write-host -f Yellow "Site Column Doesn't Exists!"
    }
}
Catch {
    write-host -f Red "Error deleting Site Column!" $_.Exception.Message
} 


You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


How to Delete a SharePoint Web Application

SharePoint Web Applications are actually an IIS Containers at top level. Each web application we create from SharePoint, creates respective site in IIS and a content database in SQL Server.

To delete a SharePoint 2016 Web Application,
  • Open SharePoint 2016 Central Administration Site
  • Click on "Manage web applications" link under "Application Management"
  • Select your target web application, and from the ribbon, click on Delete button.
    how to delete a web application in sharepoint 2013
  • Specify whether you would like to delete the content databases and IIS web sites.
    how to delete a sharepoint web application
  • Confirm the Prompt once to delete a web application in SharePoint 2013 and your web application will be deleted momentarily.
This removes the specified web application from the SharePoint farm.

SharePoint delete web application zone:
To delete SharePoint web application extension, From SharePoint Central Administration:
  • Click on Administration Management >> Manage Web Applications
  • Select the web application you wish to remove the extended zone from >> Click on Delete button drop-down and choose "Remove SharePoint from IIS Web Site"
  • Select IIS web site & zone to remove, (make sure its not your "Default" zone!)
  • Set the value for "Delete IIS web sites" to "Yes" and click OK to delete web application zone.
    sharepoint delete web application zone
To delete a SharePoint web application using PowerShell, use this script: Delete SharePoint web application using PowerShell

You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Wednesday, October 19, 2016

SharePoint Online: Delete List using PowerShell CSOM

How to Delete a list or library in SharePoint Online:
  • Click on Site Settings gear >> Select Site contents from the menu.
  • On the site contents page, Hover over the list or library that you want to delete and then click the drop-down menu icon (…)
  • On the menu that appears, click on "Remove" link and then confirm the prompt to send the list to the Recycle Bin. 
  • Alternatively, you may remove a list or library in SharePoint online by going to list settings >> Click on "Delete this list" under Permissions and Management group.
    delete list sharepoint online powershell
Now, lets delete list in sharepoint online using PowerShell

Delete List in SharePoint Online using PowerShell:
SharePoint online PowerShell to delete list
#Load SharePoint CSOM Assemblies
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
  
#Set Variables for Site URL and List Name
$SiteURL= "https://crescent.sharepoint.com/sites/pmo"
$ListName="Projects"

#Setup Credentials to connect
$Cred = Get-Credential
$Cred = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.UserName,$Cred.Password)

Try {
    #Setup the context
    $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
    $Ctx.Credentials = $Cred

    #Get the List
    $List=$Ctx.Web.Lists.GetByTitle($ListName)

    #Delete the list
    $List.DeleteObject()
    $Ctx.ExecuteQuery()
        
    Write-host -f Green "List Deleted Successfully!" 
}
Catch {
    write-host -f Red "Error deleting list!" $_.Exception.Message
}


You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Monday, October 17, 2016

SharePoint Online: Configure Access Request Email Settings using PowerShell

Access request settings in SharePoint Online
Access Request feature in SharePoint online allows people to request access to content that they do not have permission. Access request settings also allows members of the site to send invitations to users who have no permission. Once the invitations are sent, Site owner should approve it from Site settings >> Access requests and invitations. If you change these settings on the Site Collection level, then new sub sites doesn’t inherit.

To configure access request email settings in SharePoint online, Go to
  • Site Settings >> Site Permissions >> Access Requests Settings 
  • This takes you to SharePoint online access request page >> Update access request email and hit OK to save your changes.sharepoint online access request settings powershell
Please note, SharePoint online access request email Site Settings must be configured at each site level. Lets see SharePoint Online PowerShell to set access request email.


Set SharePoint online access request settings using PowerShell
Use this PowerShell script to update SharePoint online access request email.
#Load SharePoint CSOM Assemblies
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
  
#Set Variables for Site URL
$SiteURL= "https://crescent.sharepoint.com/sites/sales/"
$AccessReqEmail="SharePointSupport@crescent.com"

#Setup Credentials to connect
$Cred = Get-Credential
$Cred = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.UserName,$Cred.Password)

Try {
    #Setup the context
    $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
    $Ctx.Credentials = $Cred

    #Get the current settings
    $Web = $Ctx.Web
    $Ctx.Load($web.AllProperties)
    $web.RequestAccessEmail
    $Ctx.ExecuteQuery()

    #Set Access request Email
    $Web.RequestAccessEmail =$AccessReqEmail
    #Member settings
    $Web.MembersCanShare = $True
    $web.AssociatedMemberGroup.AllowMembersEditMembership = $True
    $web.AssociatedMemberGroup.Update()

    $Web.Update()
    $Ctx.ExecuteQuery()
}
Catch {
    write-host -f Red "Error configuring Access request settings!" $_.Exception.Message
}

Disable access request in SharePoint online:
To disable access request, simply clear the Email value!
#Load SharePoint CSOM Assemblies
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
  
#Set Variables for Site URL
$SiteURL= "https://crescent.sharepoint.com/sites/sales/"

#Setup Credentials to connect
$Cred = Get-Credential
$Cred = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.UserName,$Cred.Password)

Try {
    #Setup the context
    $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
    $Ctx.Credentials = $Cred

    #disable Access request
    $Web = $Ctx.Web
    $Web.RequestAccessEmail = ""
    $Web.MembersCanShare = $False    
    $web.AssociatedMemberGroup.AllowMembersEditMembership = $False
    $web.AssociatedMemberGroup.Update()
    $Web.Update()
    $Ctx.ExecuteQuery()
}
Catch {
    write-host -f Red "Error disabling Access request settings!" $_.Exception.Message
}


You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Get All Users and Groups in SharePoint Online Site using PowerShell-CSOM

Requirement: Get All Users and Groups Report in SharePoint Online using PowerShell-CSOM

PowerShell Script to Get All Users and Groups Report in SharePoint Online:
This PowerShell script gets all groups and users of each group in a SharePoint online site.
#Load SharePoint CSOM Assemblies
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
  
#Set Variables for Site URL
$SiteURL= "https://crescent.sharepoint.com/sites/sales/"

#Setup Credentials to connect
$Cred = Get-Credential
$Cred = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.UserName,$Cred.Password)

Try {
    #Setup the context
    $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
    $Ctx.Credentials = $Cred

    #Get all Groups
    $Groups=$Ctx.Web.SiteGroups
    $Ctx.Load($Groups)
    $Ctx.ExecuteQuery()

    #Get Each member from the Group
    Foreach($Group in $Groups)
    {
        Write-Host "--- $($Group.Title) --- "

        #Getting the members
        $SiteUsers=$Group.Users
        $Ctx.Load($SiteUsers)
        $Ctx.ExecuteQuery()
        Foreach($User in $SiteUsers)
        {
            Write-Host "$($User.Title), $($User.Email), $($User.LoginName)"
        }
    }
}
Catch {
    write-host -f Red "Error getting groups and users!" $_.Exception.Message
}
Here is my another article to get all groups and group members from SharePoint online using SharePoint online shell: SharePoint Online: Site Users and Groups Report using PowerShell

You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Sunday, October 16, 2016

SharePoint Online: Get Content Type ID using PowerShell-CSOM

My other article speaks on How to find the content type id in SharePoint, using SharePoint UI and PowerShell for SharePoint On-premises, This post provides script to get content type by id programmatically for SharePoint online.
To get the content type ID, you can Go to List/Site Content Types >> Pick your content type >> The URL will have "Ctype" parameter with the content type ID!
sharepoint online get content type id

SharePoint Online: Get content type id using CSOM
Here is the PowerShell script to get content type id in SharePoint using csom code.
#Load SharePoint CSOM Assemblies
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
  
#Config Parameters
$SiteURL= "https://crescent.sharepoint.com"
$ContentTypeName="Crescent Project Report"

#Setup Credentials to connect
$Cred = Get-Credential
$Cred = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.UserName,$Cred.Password)

Try {
    #Setup the context
    $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
    $Ctx.Credentials = $Cred

    #Get content types of the web
    $ctx.Load($ctx.Web.ContentTypes)
    $Ctx.ExecuteQuery()

    #Get the content type by its name
    $ContentType = $Ctx.Web.ContentTypes | Where {$_.Name -Match $ContentTypeName}
    $Ctx.Load($ContentType)    
    $Ctx.ExecuteQuery()

    #sharepoint online get content type id
    write-host -f Green "Content Type ID:" $ContentType.Id
}
Catch {
    write-host -f Red "Error Getting Content Type ID!" $_.Exception.Message
} 
Get content type id from SharePoint online List
Lets get Content Type id for a List content type:
#Load SharePoint CSOM Assemblies
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
  
#Config Parameters
$SiteURL= "https://crescent.sharepoint.com/sites/sales/"
$ListName="Projects"
$ContentTypeName="Project Portfolio"

#Setup Credentials to connect
$Cred = Get-Credential
$Cred = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.UserName,$Cred.Password)

Try {
    #Setup the context
    $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
    $Ctx.Credentials = $Cred

    #Get the List and Its content types
    $List = $Ctx.Web.Lists.GetByTitle($ListName)
    $Ctx.load($List)
    $Ctx.load($List.ContentTypes)
    $Ctx.ExecuteQuery()

    #Get the content type by its name
    $ContentType = $List.ContentTypes | Where {$_.Name -Match $ContentTypeName}
    $Ctx.Load($ContentType)    
    $Ctx.ExecuteQuery()

    #sharepoint online get content type id
    write-host -f Green "Content Type ID:" $ContentType.Id
}
Catch {
    write-host -f Red "Error Getting Content Type ID!" $_.Exception.Message
}


You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


How to Get Content Type ID in SharePoint using PowerShell

Requirement:
A typical usage of Content Types is reusable metadata in SharePoint. At times, You may need to get content type id by name in order to  assign the content type to lists and libraries programmatically. Lets get content type id in SharePoint 2013 using PowerShell.

How to find content type id in SharePoint List?
To get content type id from SharePoint interface:
  • Open your SharePoint List in browser >> click on "List Settings" from the List tab of the Ribbon
  • In the List Settings page click on your target content type under "Content types" - Assuming content types are enabled already.
  • Now, You'll see the ID of the content type in the URL.The last part is the Content Type Id. E.g. http://intranet.crescent.com/_layouts/15/ManageContentType.aspx?List=%7BEE1EA017%2DD347%2D49E6%2D9FE2%2D2CA7D1CB7B57%7D&ctype=0x01160074E6A09BFE52244F8ECB851FF74077FCsharepoint 2013 powershell get content type id
Same procedure applies for Site content Types as well. Go to Site settings >> Site Content Types >> Pick your content type >> The URL will have "Ctype" parameter with the content type ID of the respective content type.

SharePoint 2013 PowerShell to get content type id:
Here is the SharePoint PowerShell to find content type by id.
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Config Parameters
$WebURL="http://intranet.crescent.com"
$ListName="Projects"
$ContentTypeName="Contact Project"

#Get the Web, List and Content Type objects
$Web = Get-SPWeb $WebURL
$List = $Web.Lists.TryGetList($ListName)
#Get the content Type from its name
$ContentType = $List.ContentTypes | Where {$_.Name -Match $ContentTypeName}

#sharepoint get content type id by name
Write-Host $ContentType.ID 

Similarly, to get the site content type id in SharePoint 2013 using Powershell, use:
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Config Parameters
$WebURL="http://intranet.crescent.com"
$ContentTypeName="Crescent Configuration Entry"

#Get the Web, List and Content Type objects
$Web = Get-SPWeb $WebURL
#Get the content Type from its name
$ContentType = $Web.ContentTypes | Where {$_.Name -Match $ContentTypeName}

#sharepoint get content type id by name
Write-Host $ContentType.ID
How to get a content Type by ID?
$CT = $Web.ContentTypes | Where {$_.ID -eq "0x01005B3FBCA1E5314D57B4198D54F9F9B9CD"}

Tags: sharepoint powershell find content type by id,  find content type id sharepoint 2013, get content type id sharepoint 2013 powershell, how to get content type id from sharepoint, sharepoint get content type id programmatically

You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Monday, October 10, 2016

Get All Site Collections in a Web Applications using PowerShell

To get all site collections in web application, from SharePoint central Admin, follow these steps:
  • Go to SharePoint Central Admin Site >> Application Management 
  • Click on "View all site collections" link under Site Collections Group. Select your web application. This page lists all site collections in the selected web application.
    sharepoint get all site collections in web application
Get all site collections in web application using PowerShell:
Here is the PowerShell to list all site collections in web application.
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Set the Web application URL
$WebAppURL="http://intranet.crescent.com"

#Get the Web Application        
$WebApp = Get-SPWebApplication $WebAppURL

#Get all Site collections from the web application
$SitesCollection  = $WebApp.Sites

#Enumerate all site collections in the web application
Foreach($Site in $SitesCollection)
{
    #Get Site Collection URL, Owner, Content Database Details
    Write-host $Site.URL
}

While the above code written in classic manner, you can use PowerShell one-liner to get list of all site collections in web application:
Get-SPWebApplication "http://intranet.crescent.com" | Get-SPSite | Select URL

PowerShell to get all site collections in a web application:
This time, lets use PowerShell expressions to dig into site collection properties, say: Site Name, content database, etc.
Get-SPWebApplication "http://intranet.crescent.com" | Get-SPSite | Select URL,@{Name="Site Name"; Expression={$_.RootWeb.Title}},Owner 

How to get all site collections in a web application and Export to CSV
How about get all site collections in a web application using PowerShell and Export to CSV?
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Web application URL and CSV File location Variables
$WebAppURL="http://intranet.crescent.com"
$CSVFile="C:\SitesList.csv"

#Get list of site collections in a web application powershell
 Get-SPWebApplication $WebAppURL | Get-SPSite | ForEach-Object {
 New-Object -TypeName PSObject -Property @{
             SiteName = $_.RootWeb.Title
             Url = $_.Url
             DatabaseName = $_.ContentDatabase.Name }
} | Export-CSV $CSVFile -NoTypeInformation
This Script gets all site collections from the given web application and exports the site collection data to CSV
how to get all site collections in a web application using powershell

You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Add-Remove User to SharePoint Multi-Valued People Picker Field using PowerShell

Requirement: 
We've a SharePoint list called "Projects" with 1000's of items. The list has a field called "Team Members" which allows multiple user values. We often get a requirement to either add or remove a particular user to all items or specific items filtered by other columns in the list.

Solution: Adding-removing user from multiple items in a bulk can be achieved with PowerShell. Lets use PowerShell to add or remove user from SharePoint people picker (person or group) field value.
powershell to add remove user to people picker column value in sharepoint


PowerShell to Add new user to Person or Group Field:
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
 
#Configuration parameters
$SiteURL = "http://portal.crescent.com/projects/"
$ListName = "Projects"                
$FieldName= "TeamMembers"
$UserToAdd="Crescent\Sam"

#Get site and List objects
$web = Get-SPWeb $SiteURL
$List = $web.Lists.TryGetList($ListName)

#Item Ids to update
$IDColl= @(4,5,7,14,55,169,258,260,261)

#Iterate through each item
foreach($ItemID in $IDColl)
{
    #Get the Item
    $Item = $List.GetItembyID($ItemID)
 Write-Host "Processing: "$item["ProjectName"]
    
    #Get Existing field value
    $MultiUserCollection = [Microsoft.SharePoint.SPFieldUserValueCollection]$item[$FieldName]
          
    #Prepre the user to Add
    $User = $Web.EnsureUser($UserToAdd)

 #Add new user to the collection
 $NewUser = new-object Microsoft.SharePoint.SPFieldUserValue($Web, $User.ID,$User.Name)
 $MultiUserCollection.Add($NewUser)

 #Update the field value
 $item[$FieldName] = $MultiUserCollection
 $item.update()   
 
 write-host "Team Member Added!"     
}

PowerShell to remove user from Multi-user People Picker field:
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
 
#Configuration parameters
$SiteURL = "http://portal.crescent.com/projects/"
$ListName = "Projects"                
$FieldName= "TeamMembers"
$UserToRemove="Crescent\Sam"

#Get site and List objects
$web = Get-SPWeb $SiteURL
$List = $web.Lists.TryGetList($ListName)

$IDColl= @(184,259,281,282,306,318,331,378,404,410)
foreach($ItemID in $IDColl)
{
        #Get the Item
        $Item = $List.GetItembyID($ItemID)
        Write-Host "Processing: "$item["ProjectName"]
        
        #Get Existing field value
        $MultiUserCollection = [Microsoft.SharePoint.SPFieldUserValueCollection]$item[$FieldName]
        $NewUserCollection = new-object Microsoft.SharePoint.SPFieldUserValueCollection
       
        #Prepre the user to remove
        $User = $Web.EnsureUser($UserToRemove)
  
        #Create a new collection - exclude user to remove      
        Foreach($MultiUser in $MultiUserCollection)
        {
            if($MultiUser.User.LoginName -ne $User.LoginName)
            {
                #Add user to new collection
                $NewUser = new-object Microsoft.SharePoint.SPFieldUserValue($Web, $MultiUser.User.ID,$MultiUser.User.Name)
                $NewUserCollection.Add($NewUser)
            }
         }
        #Update the list item 
        $item[$FieldName] = $NewUserCollection
        $item.update()   
  
        write-host "User Removed From Existing People Picker field Value!"     
 }


You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Saturday, October 8, 2016

SharePoint Online: How to Check in a Document using PowerShell CSOM

Check out-Check in feature in SharePoint avoids conflicts in typical collaboration environments, where multiple users may try to edit the same document at the same time. You must check in the document back in order to make the changes available to all other users, Even if the document is saved.

How to Check-in a document in SharePoint online?
To check in a checked out file, follow these steps in SharePoint online.
  • Navigate to the document library where the checked out file is saved. Select the document(s) to Check in. 
  •  From the ribbon, click the Files tab, click on "Check In" from the "Open & Check Out" group.
  • In the Check In dialog box, click No for "keep the file checked out after checking it in" option.
  • Click OK.
If you Checking in a document but retain it to checkout, other users get to see your latest changes while you may continue to work on the rest of the changes to your document.
how to checkin a document in sharepoint online powershell

SharePoint online PowerShell to check in a document

#Load SharePoint CSOM Assemblies
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
  
#Function to Check if file exists in given URL
Function Checkin-Document($SiteURL, $FileRelativeURL, $Credentials)
{

    #Setup the context
    $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
    $Ctx.Credentials = $Credentials

    Try {
        #Try to get the File from URL
        $File = $Ctx.web.GetFileByServerRelativeUrl($FileRelativeURL)
        $Ctx.Load($File)
        $Ctx.ExecuteQuery()
        
        #check if the file is checked out
        If($File.CheckOutType -eq "None")
        {
            write-host "Document is not checked out Already!" -f Red
            break
        }
        #Checkin the document
        $File.CheckIn("",[Microsoft.SharePoint.Client.CheckinType]::MajorCheckIn)
        #Checkin Types: MajorCheckIn,MinorCheckIn,OverwriteCheckIn

        $Ctx.ExecuteQuery()

        write-host "Document has been checked-in successfully!" -f Green
    }
    Catch {
        write-host -f Red "Error checking-in Document!" $_.Exception.Message
    }
}

#Set Variables for Site URL, List Name and Column Name
$SiteURL= "https://crescent.sharepoint.com/sites/sales/"
$FileRelativeURL="/sites/Sales/Shared%20Documents/Legal%20Template.xssn"

#Setup Credentials to connect
$Cred = Get-Credential
$Cred = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.UserName,$Cred.Password)

#Call the function to Checkin file
Checkin-Document -SiteURL $SiteURL -FileRelativeURL $FileRelativeURL -Credentials $Cred

SharePoint online PowerShell to check in file
The above script gets the file from URL. Alternatively, you can get file from Item ID and check in. Here is an another PowerShell way of check in file in SharePoint Online.
#Load SharePoint CSOM Assemblies
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
  
#Set Variables for Site URL, Library Name and Item ID
$SiteURL= "https://Crescent.sharepoint.com/sites/sales/"
$LibraryName="Documents"
$ItemID="4"

#Setup Credentials to connect
$Cred = Get-Credential
$Cred = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.UserName,$Cred.Password)

#Setup the context
$Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$Ctx.Credentials = $Cred

#Get the web, List, Item adn File
$Web=$Ctx.Web
$List=$web.Lists.GetByTitle($LibraryName)
$Item=$list.GetItemById($ItemID)
$File=$Item.File

#Get the File to context
$Ctx.Load($File)
$Ctx.ExecuteQuery()
        
#check if the file is checked out
If($File.CheckOutType -eq "None")
{
    write-host "Document is not checked out Already!" -f Red
}
else
{
    #Check in the file
    $File.CheckIn("Checked-in from PowerShell",[Microsoft.SharePoint.Client.CheckinType]::MajorCheckIn)
    $Ctx.ExecuteQuery()
    
    write-host "Document has been checked-in successfully!" -f Green
}


You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


SharePoint Online: How to Checkout a Document using Powershell CSOM

Checking out a document in SharePoint ensures that you are the only one making edits to it. The purpose of checkout is to prevent conflicts in a collaboration environment where multiple people may try to edit the same document or list item at the same time. So, When a file is checked out to you, you are the only one allowed making changes to it. The file will remain locked until you release it.

When you're finished making edits, check in the document so that other users can view the changes you made. The option of "Require checkout" can be turned ON or OFF from document library settings.

How to Check out a document?
  • Navigate to the document library in your SharePoint or SharePoint online site. Select the document which you would like to checkout. 
  • On the ribbon, click on Files tab, Click on "Check Out" button. (or you can checkout from the item's context menu)
  • Once the document is checked out, you'll get a tiny outward-pointing  green arrow, in the document icon.
how to checkout a file in sharepoint online powershell


PowerShell script to checkout a document in SharePoint online:
#Load SharePoint CSOM Assemblies
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
  
#Function to Check if file exists in given URL
Function Checkout-Document($SiteURL, $FileRelativeURL, $Credentials)
{

    #Setup the context
    $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
    $Ctx.Credentials = $Credentials

    Try {
        #Try to get the File from URL
        $File = $Ctx.web.GetFileByServerRelativeUrl($FileRelativeURL)
        $Ctx.Load($File)
        $Ctx.ExecuteQuery()
        
        #check if the file is already checked out
        If($File.CheckOutType -ne "None")
        {
            write-host "File is already checked-out!" -f Yellow
            break
        }
        #Checkout the document
        $File.CheckOut()
        $Ctx.ExecuteQuery()

        write-host "Document has been checked-out successfully!" -f Green
    }
    Catch {
        write-host -f Red "Error checking out Document!" + $_.Exception.Message
    }    
}

#Set Variables for Site URL, List Name and Column Name
$SiteURL= "https://crescent.sharepoint.com/sites/sales/"
$FileRelativeURL="/sites/Sales/Shared%20Documents/Legal%20Template.xsn"

#Setup Credentials to connect
$Cred = Get-Credential
$Cred = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.UserName,$Cred.Password)

#Call the function to Checkout file
Checkout-Document -SiteURL $SiteURL -FileRelativeURL $FileRelativeURL -Credentials $Cred 

SharePoint Online: Checkout Document using PowerShell CSOM:
Alternatively, instead of document URL, some times you may have to checkout from the Item ID. Here is the script to checkout a document from the item id.
#Load SharePoint CSOM Assemblies
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
  
#Set Variables for Site URL, Library Name and Item ID
$SiteURL= "https://crescent.sharepoint.com/sites/sales/"
$LibraryName="Documents"
$ItemID="4"

#Setup Credentials to connect
$Cred = Get-Credential
$Cred = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.UserName,$Cred.Password)

#Setup the context
$Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$Ctx.Credentials = $Cred

#Get the web, List, Item adn File
$Web=$Ctx.Web
$List=$web.Lists.GetByTitle($LibraryName)
$Item=$list.GetItemById($ItemID)
$File=$Item.File

#Check out the file
$File.CheckOut()
$Ctx.ExecuteQuery()


You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


SharePoint Online: Check if File Exists in Document Library using PowerShell CSOM

Requirement: Check if a file exists in SharePoint online document library using PowerShell CSOM.

PowerShell to check if a file exists in SharePoint online document library:
Lets check if file exists in SharePoint document library with PowerShell.
#Load SharePoint CSOM Assemblies
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
  
#Function to Check if file exists in given URL
Function Check-FileExists($SiteURL, $FileRelativeURL, $Credentials)
{
    #Setup the context
    $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
    $Ctx.Credentials = $Credentials

    Try {
        #Try to get the File from URL
        $File = $Ctx.web.GetFileByServerRelativeUrl($FileRelativeURL)
        $Ctx.Load($File)
        $Ctx.ExecuteQuery()
        Return $True
    }
    Catch {
        Return $False
    }    
}

#Set Variables for Site URL, List Name and Column Name
$SiteURL= "https://crescent.sharepoint.com/sites/sales/"
$FileRelativeURL="/sites/Sales/TeamDocuments/LegalTemplate.docx"

#Setup Credentials to connect
$Cred = Get-Credential
$Cred = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.UserName,$Cred.Password)

#Call the function to Check Column Exists in given list
$FileExists = Check-FileExists -SiteURL $SiteURL -FileRelativeURL $FileRelativeURL -Credentials $Cred

if($FileExists) {
    write-host "File Exists in the Given URL!" -f Green
    #Proceed with your script
 }
 else {
    write-host "File Doesn't Exists in the given URL!" -f Red
 }
Tags: check if file exists in sharepoint document library csom powershell, how to check file exists in sharepoint library, sharepoint check file exists document library, sharepoint csom check file exists, sharepoint powershell check if file exists in library

You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


SharePoint Online: Check If Field Exists in List using PowerShell

Requirement:
PowerShell to check if a field exists in list in SharePoint online.

SharePoint Online - PowerShell to check if a Column exists in List
#Load SharePoint CSOM Assemblies
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
  
#Function to Check if a column exists in a List
Function Check-ColumnExists($SiteURL, $ListName, $FieldName, $Credentials)
{
    #Setup the context
    $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
    $Ctx.Credentials = $Credentials

    #Retrive all Fields from the list
    $List = $Ctx.Web.Lists.GetByTitle($ListName)
    $Fields = $List.Fields
    $Ctx.Load($List)
    $Ctx.Load($Fields)
    $Ctx.ExecuteQuery()

    #Check if the given field name 
    $Field = $Fields | where{$_.Title -eq $FieldName}
    if($Field)  { return $true } else { return $false}
}

#Set Variables for Site URL, List Name and Column Name
$URL= "https://crescent.sharepoint.com/sites/sales/"
$List="Project Documents"
$Field="Department" #Display Name

#Setup Credentials to connect
$Cred = Get-Credential
$Cred = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.UserName,$Cred.Password)

#Call the function to Check Column Exists in given list
$ColumnExists = Check-ColumnExists -SiteURL $URL -ListName $List -FieldName $Field -Credentials $Cred

if($ColumnExists) {
    write-host "Column Exists in Given List!" -f Green
    #Proceed with your script
 }
 else {
    write-host "Column Doesn't Exists in given List!" -f Red
 }


You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


SharePoint Online: Check if List Exists using PowerShell

Requirement:
Check if a particular list exists in a given SharePoint online site using PowerShell csom script.

PowerShell Script to check if List Exists in SharePoint Online:
#Load SharePoint CSOM Assemblies
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
  
#Custom Function to Check if Site Collection Exists in Given URL
Function Check-ListExists($SiteURL, $ListName, $Credentials)
{
    #Setup the context
    $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
    $Ctx.Credentials = $Credentials

    Try {
            $List = $Ctx.Web.Lists.GetByTitle($ListName)
            $Ctx.Load($List)
            $Ctx.ExecuteQuery()
            Return $True
        }
    Catch [Exception] {
      Write-host $_.Exception.Message -f Red
      Return $False
     }
}

#Set Variables for Site URL and List Name
$URL= "https://crescent.sharepoint.com/sites/sales/"
$List="Documents"

#Setup Credentials to connect
$Cred = Get-Credential
$Cred = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.UserName,$Cred.Password)

#Call the function to Check List Exists in given web  
$ListExists = Check-ListExists -SiteURL $URL -ListName $List -Credentials $Cred

if($ListExists) {
    write-host "List Exists in Given Site!!" -f Green
    #Proceed with your script
 }
 else {
    write-host "List Doesn't Exists on given web!" -f Red
 }


You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


SharePoint Online: Check if Site Collection, Subsite Exists using PowerShell CSOM

Requirement: Check if site or site collection exists in SharePoint online using PowerShell CSOM.

SharePoint Online PowerShell-CSOM to check if site or site collection exists in given URL:
This PowerShell script checks if site collection exists in the given URL.

#Load SharePoint online Assemblies
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
  
#Custom Function to Check if Site Collection Exists in Given URL
Function Check-SiteExists($SiteURL, $Credentials)
{
    #Setup context
    $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
    $Ctx.Credentials = $Credentials
    $Web = $Ctx.Web
    $Ctx.Load($web)
    
    Try {
            $Ctx.ExecuteQuery()
            Return $True
        }
    Catch [Exception] {
      Write-host $_.Exception.Message -f Red
      Return $False
     }        
}

#Variable for Site collection URL
$URL= "https://crescent.sharepoint.com/sites/sales/"

#Setup Credentials to connect
$Cred = Get-Credential
$Cred = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.UserName,$Cred.Password)
  
$SiteExists = Check-SiteExists -SiteURL $URL -Credentials $Cred

#Call the function to check site exists
if($SiteExists -eq $True)
 {
    write-host "Given Site Collection Exists!" -f Green
    #Proceed with your script
 }
 else
 {
    write-host "Site Collection doesn't Exists on given URL!" -f Red
 }
Please note, the function Check-SiteExists may return false in case of any network related issue or authentication failures.

My another server side script to Check if site collection or subsite exists in SharePoint using PowerShell in SharePoint on-premises.

Tags: sharepoint check site exists, sharepoint check site collection exists, powershell sharepoint check site exists, sharepoint csom check if site exists, sharepoint check if url valid, sharepoint powershell check if site exists, check if subsite exists sharepoint powershell csom

You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Monday, October 3, 2016

Update SharePoint List Items from CSV File using PowerShell

Requirement: Update SharePoint List Items from CSV file.

Bit background: We've a list with 1000's of rows of organization wide experts. Later we added a new field for "Department". Now the requirement is to update Department field for specific list of users. While the datasheet view can be used for bulk editing, filtering and editing 100's of rows would be time consuming. So the solution is: Have list of user names and their departments in CSV file format, give it to PowerShell!

PowerShell Script to Read from CSV file and Update SharePoint List Items:
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
 
#Read the CSV file
$CSVData = Import-CSV -path "C:\UserData.csv" 
 
#Get the Web
$web = Get-SPWeb -identity "http://portal.crescent.com"
 
#Get the Target List
$List = $web.Lists["ExpertProfiles"]
 
#Iterate through each Row in the CSV
foreach ($Row in $CSVData) 
{
    #Get the List Item matching "Name" field in the CSV    
    $Item = $List.Items | Where-Object { $_["Title"] -eq $Row.Name }

    if($item -ne $null)
    {
 #Update List Item - Internal Name!
        $item["Department"] = $row.Department
        $item.Update()
        Write-Host "Updated:"$row.Name -ForegroundColor Green
    }
    else
    {
        write-host "No matching Item Found for:"$row.Name -f Red
    }
}
While the above code serves the purpose, Lets optimize it with CAML-SPQuery

PowerShell to Update SharePoint List from CSV:
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
 
#Read the CSV file
$CSVData = Import-CSV -path "C:\UserData.csv" 
 
#Get the Web
$web = Get-SPWeb -identity "http://portal.crescent.com"
 
#Get the Target List
$List = $web.Lists["ExpertProfiles"]
 
#Iterate through each Row in the CSV
foreach ($Row in $CSVData) 
{
    #Filter using CAML Query
    $CAMLQuery="<Where><Eq><FieldRef Name='Title'/><Value Type='Text'>$($Row.Name)</Value></Eq></Where>"
    $SPQuery=New-Object Microsoft.SharePoint.SPQuery
    $SPQuery.ViewAttributes = "Scope='Recursive'"  #Get all items including Items in Sub-Folders!
    $SPQuery.Query=$CAMLQuery
    $SPQuery.RowLimit = 1 
     
    #Get the List item based on Filter 
    $Item=$List.GetItems($SPQuery)[0]

    If($Item -ne $null)
    {
        #Update List Item
        $Item["Department"] = $Row.Department
        #$item.Update()
        Write-Host "Updated:"$row.Name -ForegroundColor Green
    }
    else
    {
        write-host "No matching Item Found for:"$row.Name -f Red
    }
}
Update People Picker Field Value from CSV file:
In an another case, I had to update people picker field value:
 #If the matching project found
    If($Item -ne $null)
    {
        #Update Team members Multi-People picker field
  $TeamMembersList = new-object Microsoft.SharePoint.SPFieldUserValueCollection
  $TeamMembers = $row."TeamMembers" -split ';'
  foreach ($TeamMember in $TeamMembers)
  {
   if ($TeamMember -ne $null) 
   {
    #Prepre the user to add
       $User = $Web.EnsureUser($TeamMember)
       $NewUser = new-object Microsoft.SharePoint.SPFieldUserValue($Web, $User.ID, $User.LoginName)
    $TeamMembersList.Add($NewUser)
   }
  }
  #Update Team members field
  $item["Team Members"] = $TeamMembersList
  $item.Update()
        Write-Host "Updated:"$Row.ProjectName -ForegroundColor Green
    }
    else
    {
        write-host "No matching Item Found for:"$row.ProjectName -f Red
    } 

Related Posts:


You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


You might also like:

Related Posts Plugin for WordPress, Blogger...