Quantcast
Channel: SharePoint Diary
Viewing all 1058 articles
Browse latest View live

SharePoint Online: Export List Version History to Excel using PowerShell

$
0
0
Requirement: Export all versions of SharePoint Online List Items to CSV (Excel) file.
sharepoint online export list version history to excel using powershell

Important: This script works ONLY on CSOM version 16.1.6906.1200 or Later! Download the latest version of CSOM SDK from https://www.microsoft.com/en-us/download/confirmation.aspx?id=42038

PowerShell to Extract and Export List Item's Version History to CSV File:
#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 Export-VersionHistory()
{
param
(
[Parameter(Mandatory=$true)] [string] $SiteURL,
[Parameter(Mandatory=$true)] [string] $ListName,
[Parameter(Mandatory=$true)] [string] $CSVFile
)
Try {

#Delete the Output report file if exists
if (Test-Path $CSVFile) { Remove-Item $CSVFile }

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

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

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

#Get all items
$Query = [Microsoft.SharePoint.Client.CamlQuery]::CreateAllItemsQuery()
$ListItems = $List.GetItems($Query)
$Ctx.Load($ListItems)
$Ctx.ExecuteQuery()

#Array to hold result
$VersionHistoryData = @()

#Iterate throgh each item
Foreach ($Item in $ListItems)
{
write-host "Processing Item:" $item.id -f Yellow

#Get all versions of the list item
$Versions = $Item.versions
$ctx.Load($Versions)
$Ctx.ExecuteQuery()

If($Versions.count -gt 0)
{
#Iterate each version
Foreach($Version in $Versions)
{
#Get the Creator object of the version
$CreatedBy = $Version.createdby
$Ctx.Load($CreatedBy)
$Ctx.ExecuteQuery()

#Send Data to object array
$VersionHistoryData += New-Object PSObject -Property @{
'Item ID' = $Item.ID
'Title' = $Version.FieldValues["Title"]
'Version Label' = $Version.VersionLabel
'Version ID' = ($Version.VersionId/512)
'Created On' = (Get-Date ($Version.Created) -Format "yyyy-MM-dd/HH:mm:ss")
'Created By' = $CreatedBy.Email
}
}
}
}

#Export the data to CSV
$VersionHistoryData | Export-Csv $CSVFile -Append -NoTypeInformation

write-host -f Green "Version History Exported Successfully to:" $CSVFile
}
Catch {
write-host -f Red "Error Exporting version History to CSV!" $_.Exception.Message
}
}

#Set parameter values
$SiteURL="https://crescent.sharepoint.com"
$ListName="Projects"
$CSVFile="C:\Temp\VersionHistory.csv"

#Call the function to generate version History Report
Export-VersionHistory -SiteURL $SiteURL -ListName $ListName -CSVFile $CSVFile

This script produces a CSV file with version data such as:
  • Version Label,
  • Version ID
  • When the version was created
  • Who created the version
  • Title field value of the version (You can add any additional field too!)

SharePoint Online: Create Content Type using PowerShell

$
0
0
What are content types in SharePoint Online?
Content types are set of columns grouped together to serve a specific purpose. Think about a Invoice template! Instead of you and your users end up creating different templates each time from the scratch, you can define an Invoice template once and your users can start consuming it at any number of lists or document libraries! By this way, you force standardization in your collaboration environment. Or think of "Project Tracking" list with columns required to track projects for your organization. Instead creating and adding each column for Project tracking list every time, you'll be able to simply utilize project tracking content type template in any number of lists in few clicks.

SharePoint Online lists or document libraries can contain multiple content types. E.g. You can add multiple content types such as "Invoice", "Proposal", "Purchase Order", etc to a library to organize everything related to a project as a single entity. Once you associate a content type with SharePoint online list or library, SharePoint lets you to create new items of that content type from New Item command in that list or library. In the case of a document content type, you can also define a document template that will be the base for all the documents created from this particular content type.

As a best practice, content types should be ideally defined at the top site, independent of any list or library, So that it can be reused at any SharePoint site underneath or even across SharePoint site collections with content type hub.

How to Create Content Type in SharePoint Online?
To add a content typein SharePoint online, follow these steps:
  • Go to Site Settings >> Click on "Site Content Types" under "Web Designer Galleries" group.
  • In Site content types page, You''ll see the list of default content types like Item, Tasks, Document, etc grouped by sections. Click on "Create" link at the top.
  • Provide a name to your custom content type. Optionally you can enter the description for your new content type to make it clear.
  • Select the parent content type such as "Item" to which your content type is based on. You can either create a new content type group or select any existing.
    sharepoint online powershell create content type
  • Click OK to complete adding content type. Once the content type is created, The next step is to add required Site columns to the content type to make metadata available from the content type.

SharePoint online Create Content Type using PowerShell
Here is the PowerShell script to create content type programmatically 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 turn ON Content Type in SharePoint Online list or library
Function Create-SPOContentType()
{
param
(
[Parameter(Mandatory=$true)] [string] $SiteURL,
[Parameter(Mandatory=$true)] [string] $CTypeName,
[Parameter(Mandatory=$true)] [string] $CTypeDesc,
[Parameter(Mandatory=$true)] [string] $ParentCTypeName,
[Parameter(Mandatory=$true)] [string] $CTypeGroup
)

Try {
$Cred= Get-Credential
$Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)

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

#Get all content types from the site
$ContentTypeColl = $Ctx.web.ContentTypes
$Ctx.Load($ContentTypeColl)
$Ctx.ExecuteQuery()

#Get the parent content type
$ParentCType = $ContentTypeColl| Where {$_.Name -eq $ParentCTypeName}

#Check if content type exists already
$ContentType = $ContentTypeColl| Where {$_.Name -eq $CTypeName}


If($ContentType -ne $Null)
{
Write-host "Content type '$CTypeName' already exists!" -ForegroundColor Yellow
}
else
{
#Specify properties for the new content type
$CTypeCreationInfo=New-Object Microsoft.SharePoint.Client.ContentTypeCreationInformation
$CTypeCreationInfo.Name=$CTypeName
$CTypeCreationInfo.Description=$CTypeDesc
$CTypeCreationInfo.Group=$CTypeGroup
$CTypeCreationInfo.ParentContentType=$ParentCType

# Add the new content type to the collection
$ContentType=$ContentTypeColl.Add($CTypeCreationInfo)
$Ctx.ExecuteQuery()

Write-host "Content Type '$CTypeName' Created Successfully!" -ForegroundColor Green
}
}
Catch {
write-host -f Red "Error Creating Content Type!" $_.Exception.Message
}
}

#Set parameter values
$SiteURL="https://crescent.sharepoint.com"
$CTypeName="Projects"
$CTypeDesc="Contnet type for Project template"
$ParentCTypeName="Item"
$CTypeGroup="Crescent Projects"

#Call the function
Create-SPOContentType -SiteURL $SiteURL -CTypeName $CTypeName -CTypeDesc $CTypeDesc -ParentCTypeName $ParentCTypeName -CTypeGroup $CTypeGroup
This script creates content type in sharepoint online from the specified parent content type. Here in this example, I've created "Project" content type from "Item" content type which has "Title" as its default field. You may want to add additional fields tot the content type and you can add columns to content type in SharePoint online with PowerShell.

Fix "Another site or list is still using this content type. If you would still like to delete it, please remove the content type from all sites and lists and then try again" in SharePoint

$
0
0
Problem:
When trying to delete a content type from List or site, received below error in SharePoint online site
"Another site or list is still using this content type. If you would still like to delete it, please remove the content type from all sites and lists and then try again."
Another site or list is still using this content type. If you would still like to delete it, please remove the content type from all sites and lists and then try again.
Solution:
Find the references where a particular content type is being used and remove the content type association from the list. (You may have to delete the items of the particular content type or change the content type of the items, in order to remove the content type association from list). Also remove the items from both 1st stage (End-user) Recycle bin and 2nd stage (Administrator) recycle bins!

PowerShell to Find a Content Type Usage in SharePoint Online:
This PowerShell script scans get exports a content type references with in a given site collection.
#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 Get-ContentTypeUsage()
{
param
(
[Parameter(Mandatory=$true)] [string] $SiteURL,
[Parameter(Mandatory=$true)] [string] $ContentTypeName,
[Parameter(Mandatory=$true)] [string] $ReportFile
)

Try {
$Cred= Get-Credential
$Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)
Write-host "Processing Site:"$SiteURL
#Setup the context
$Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$Ctx.Credentials = $Credentials

#Get the content type from web
$ContentTypeColl = $Ctx.Web.ContentTypes
$Ctx.Load($ContentTypeColl)
$Ctx.ExecuteQuery()

#Array to hold result
$Results = @()

#Get all lists and libraries from the site
$Ctx.Load($ctx.Web.Lists)
$Ctx.Load($Ctx.Web.Webs)
$Ctx.ExecuteQuery()

Foreach($List in $Ctx.Web.Lists)
{
$Ctx.Load($List.ContentTypes)
$Ctx.ExecuteQuery()

#Check if the content type exists in the list
$ContentType = $List.ContentTypes | Where {$_.Name -eq $ContentTypeName}
If($ContentType -ne $Null)
{
$Results += New-Object PSObject -Property @{
'Site' = $SiteURL
'List Name' = $List.Title
'URL'= $SiteURL+$List.DefaultViewURL
}
Write-host "Found Content Type Reference at '$($List.Title)' in site '$SiteURL'" -f Green
}
}
#Export Results to CSV
$Results | Export-Csv $ReportFile -Append -NoTypeInformation

#Process subsites - Call the function recursively
If($Ctx.Web.Webs.Count -gt 0)
{
Foreach ($web in $Ctx.Web.Webs)
{
Get-ContentTypeUsage -SiteURL $web.Url -ContentTypeName $ContentTypeName -ReportFile $ReportFile
}
}
}
Catch {
write-host -f Red "Error Deleting Content Type!" $_.Exception.Message
}
}

#Set parameter values
$SiteURL="https://crescent.sharepoint.com/"
$ContentTypeName="Project Template"
$ReportFile="C:\Temp\ContentTypeRef.csv"

#Delete the Output report file if exists
if (Test-Path $ReportFile) { Remove-Item $ReportFile }

#Call the function
Get-ContentTypeUsage -SiteURL $SiteURL -ContentTypeName $ContentTypeName -ReportFile $ReportFile

Here is the similar similar solution for SharePoint on-premises: How to resolve Content Type in Use Error in SharePoint?

SharePoint Online: Get User Profile Properties using PowerShell

$
0
0
Requirement: SharePoint Online Get All User Profiles and export to CSV.

How to Get All user Profiles and User Profile Properties in SharePoint Online?
  • Login to SharePoint Online AdminCenter >> Click on "User Profiles" link from left navigation
  • In User Profiles, Click on "Manage User Profiles" under People tab. Use Search to get the user profile of the user.
    SharePoint online get all user profiles powershell
This interface helps us to get individual user profiles and properties one by one. Lets use PowerShell to get all user profiles in SharePoint Online.

SharePoint Online PowerShell to Get User Profile Properties
This PowerShell gets the specific property "Department" of the particular user from given site collection.
#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"
Add-Type -Path "C:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.UserProfiles.dll"

Function Get-SPOUserProfileProperty()
{
param
(
[Parameter(Mandatory=$true)] [string] $AdminSiteURL,
[Parameter(Mandatory=$true)] [string] $UserAccount,
[Parameter(Mandatory=$true)] [string] $Property
)
Try {
#Setup Credentials to connect
$Cred= Get-Credential
$Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)

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

#Get the User
$User = $Ctx.web.EnsureUser($UserAccount)
$Ctx.Load($User)
$Ctx.ExecuteQuery()

#Get User Profile
$PeopleManager = New-Object Microsoft.SharePoint.Client.UserProfiles.PeopleManager($Ctx)
$UserProfile = $PeopleManager.GetPropertiesFor($User.LoginName)
$Ctx.Load($UserProfile)
$Ctx.ExecuteQuery()

#Get the User Profile Property
Write-host $UserProfile.UserProfileProperties[$Property]

}
Catch {
write-host -f Red "Error Getting User Profile Properties!" $_.Exception.Message
}
}
#Call the function
$AdminSiteURL="https://crescent-admin.sharepoint.com"
$UserAccount="Kacper@crescent.com"
$Property="Department"

Get-SPOUserProfileProperty -AdminSiteURL $AdminSiteURL -UserAccount $UserAccount -Property $Property
This PowerShell gets the particular property of a specific user. How to get all user profiles of a site collection?

Get All User Profiles in SharePoint Online Site Collection using PowerShell
Here is how to user profile in SharePoint online using 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"
Add-Type -Path "C:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.UserProfiles.dll"

Function Export-SPOUserProfileProperties()
{
param
(
[Parameter(Mandatory=$true)] [string] $SiteURL,
[Parameter(Mandatory=$true)] [string] $CSVPath
)
Try {
#Setup Credentials to connect
$Cred= Get-Credential
$Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)

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

#Delete the CSV report file if exists
if (Test-Path $CSVPath) { Remove-Item $CSVPath }

#Get all Users
$Users = $Ctx.Web.SiteUsers
$Ctx.Load($Users)
$Ctx.ExecuteQuery()

Write-host "Total Number of Profiles Found:"$Users.count -f Yellow
#Get User Profile Manager
$PeopleManager = New-Object Microsoft.SharePoint.Client.UserProfiles.PeopleManager($Ctx)
#Array to hold result
$UserProfileData = @()

Foreach ($User in $Users)
{
Write-host "Processing User Name:"$User.LoginName
#Get the User Profile
$UserProfile = $PeopleManager.GetPropertiesFor($User.LoginName)
$Ctx.Load($UserProfile)
$Ctx.ExecuteQuery()
if($UserProfile.Email -ne $Null)
{
#Send Data to object array
$UserProfileData += New-Object PSObject -Property @{
'User Account' = $UserProfile.UserProfileProperties["UserName"]
'Full Name' = $UserProfile.UserProfileProperties["PreferredName"]
'E-mail' = $UserProfile.UserProfileProperties["WorkEmail"]
'Department' = $UserProfile.UserProfileProperties["Department"]
'Location' = $UserProfile.UserProfileProperties["Office"]
'Phone' = $UserProfile.UserProfileProperties["WorkPhone"]
'Job Title' = $UserProfile.UserProfileProperties["Title"]
}
}
}
#Export the data to CSV
$UserProfileData | Export-Csv $CSVPath -Append -NoTypeInformation

write-host -f Green "User Profiles Data Exported Successfully to:" $CSVPath
}
Catch {
write-host -f Red "Error Exporting User Profile Properties!" $_.Exception.Message
}
}

#Call the function
$SiteURL="https://crescent.sharepoint.com"
$CSVPath="C:\Temp\UserProfiles.csv"

Export-SPOUserProfileProperties -SiteURL $SiteURL -CSVPath $CSVPath
This PowerShell script gets user profiles from given site collection and exports them to Excel file (CSV). Well, How do we extract user profiles for all site collections? There is no direct way to connect to User Profile Service Application in SharePoint Online and get all user profile properties for all users in the tenant using CSOM. Either you'll have iterate through all Site Collections (and remove duplicates among them!) or use Web Services to connect to SharePoint Online and retrieve all user profiles.

However, There is a better way: Lets use the Combination of SharePoint Online CSOM and Azure AD Connect!

Pr-Requisites: Make sure you have SharePoint Online Client SDK (https://www.microsoft.com/en-us/download/details.aspx?id=42038) and Azure Active Directory Module (https://technet.microsoft.com/en-us/library/dn975125.aspx) installed on your client machine, before using this script!

SharePoint Online Get User Profile Properties using PowerShell 
Rather getting user profiles belong to a particular site collection, lets get all user profiles of the tenant and export user profile properties to CSV file.
#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"
Add-Type -Path "C:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.UserProfiles.dll"
#Import Azure AD Module
Import-Module MSOnline

Function Export-AllUserProfiles()
{
param
(
[Parameter(Mandatory=$true)] [string] $TenantURL,
[Parameter(Mandatory=$true)] [string] $CSVPath
)
Try {
#Setup Credentials to connect
$Cred= Get-Credential
$Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)

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

#Delete the CSV report file if exists
if (Test-Path $CSVPath) { Remove-Item $CSVPath }

#Get all Users
Connect-MsolService -Credential $Cred
$Users = Get-MsolUser -All | Select-Object -ExpandProperty UserPrincipalName

Write-host "Total Number of Profiles Found:"$Users.count -f Yellow
#Get User Profile Manager
$PeopleManager = New-Object Microsoft.SharePoint.Client.UserProfiles.PeopleManager($Ctx)
#Array to hold result
$UserProfileData = @()

Foreach ($User in $Users)
{
Write-host "Processing User Name:"$User
#Get the User Profile
$UserLoginName = "i:0#.f|membership|" + $User #format to claims
$UserProfile = $PeopleManager.GetPropertiesFor($UserLoginName)
$Ctx.Load($UserProfile)
$Ctx.ExecuteQuery()
if($UserProfile.Email -ne $Null)
{
#Send Data to object array
$UserProfileData += New-Object PSObject -Property @{
'User Account' = $UserProfile.UserProfileProperties["UserName"]
'Full Name' = $UserProfile.UserProfileProperties["PreferredName"]
'E-mail' = $UserProfile.UserProfileProperties["WorkEmail"]
'Department' = $UserProfile.UserProfileProperties["Department"]
'Location' = $UserProfile.UserProfileProperties["Office"]
'Phone' = $UserProfile.UserProfileProperties["WorkPhone"]
'Job Title' = $UserProfile.UserProfileProperties["Title"]
}
}
}
#Export the data to CSV
$UserProfileData | Export-Csv $CSVPath -Append -NoTypeInformation

write-host -f Green "User Profiles Data Exported Successfully to:" $CSVPath
}
Catch {
write-host -f Red "Error Exporting User Profile Properties!" $_.Exception.Message
}
}

#Call the function
$TenantURL="https://crescent.sharepoint.com"
$CSVPath="C:\Temp\UserProfiles.csv"

Export-AllUserProfiles -TenantURL $TenantURL -CSVPath $CSVPath
This script extracts all user profiles from SharePoint online Tenant to a CSV File with following properties:
  • Account
  • Full Name
  • E-Mail
  • Department
  • Location,
  • Job Title
You can add additional properties. Here is the Report output created by the PowerShell Script:
get user profile sharepoint online powershell

SharePoint Online: Update User Profile Properties using PowerShell

$
0
0
Requirement: Update User Profile Property in SharePoint Online using PowerShell

How to Update User Profiles in SharePoint Online?
To update SharePoint Online user profile properties, follow these steps:
  • Login to SharePoint Online Admin Center >> Click on "User Profiles" link from the left navigation
  • In User Profiles, Click on "Manage User Profiles" under People tab. Use Search to find the user profile of the user to update >> Click on "Edit My Profile" link from the context menu drop down of the user result.
  • Update any allowed user profile property and click on "Save and Close" button.
    powershell sharepoint online user profile properties
SharePoint Online: Update user profile using PowerShell

Here is the PowerShell for SharePoint Online to set User profile properties.
#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"
Add-Type -Path "C:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.UserProfiles.dll"

Function Update-UserProfileProperty()
{
param
(
[Parameter(Mandatory=$true)] [string] $AdminCenterURL,
[Parameter(Mandatory=$true)] [string] $UserAccount,
[Parameter(Mandatory=$true)] [string] $PropertyName,
[Parameter(Mandatory=$true)] [string] $PropertyValue
)
Try {
#Setup Credentials to connect
$Cred= Get-Credential
$Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)

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

#Get the User
$User = $Ctx.web.EnsureUser($UserAccount)
$Ctx.Load($User)
$Ctx.ExecuteQuery()

#Get User Profile
$PeopleManager = New-Object Microsoft.SharePoint.Client.UserProfiles.PeopleManager($Ctx)

#update User Profile Property
$PeopleManager.SetSingleValueProfileProperty($User.LoginName, $PropertyName, $PropertyValue)
$Ctx.ExecuteQuery()

Write-host "User Profile Property has been Updated!" -f Green
}
Catch {
write-host -f Red "Error Updating User Profile Property!" $_.Exception.Message
}
}
#Define Parameter values
$AdminCenterURL="https://crescent-admin.sharepoint.com"
$UserAccount="Zahia@Crescent.com"
$PropertyName="Department"
$PropertyValue="Operations - IT"

#Call the function
Update-UserProfileProperty -AdminCenterURL $AdminCenterURL -UserAccount $UserAccount -PropertyName $PropertyName -PropertyValue $PropertyValue

PowerShell for SharePoint Online User profile properties Update:
There are fields with Multi-values in People profiles. E.g. Skills! Lets update Multi-valued fields in SharePoint Online user profiles.
#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"
Add-Type -Path "C:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.UserProfiles.dll"

Function Update-MultiUserProfileProperty()
{
param
(
[Parameter(Mandatory=$true)] [string] $AdminCenterURL,
[Parameter(Mandatory=$true)] [string] $UserAccount,
[Parameter(Mandatory=$true)] [string] $PropertyName,
[Parameter(Mandatory=$true)] [System.Collections.Generic.List``1[System.string]] $PropertyValues
)
Try {
#Setup Credentials to connect
$Cred= Get-Credential
$Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)

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

#Get the User
$User = $Ctx.web.EnsureUser($UserAccount)
$Ctx.Load($User)
$Ctx.ExecuteQuery()

#Get User Profile
$PeopleManager = New-Object Microsoft.SharePoint.Client.UserProfiles.PeopleManager($Ctx)
$PropertyValues
#update User Profile Property
$PeopleManager.SetMultiValuedProfileProperty($User.LoginName, $PropertyName, $PropertyValues)
$Ctx.ExecuteQuery()

Write-host "User Profile Property has been Updated!" -f Green
}
Catch {
write-host -f Red "Error Updating User Profile Property!" $_.Exception.Message
}
}
#Define Parameter values
$AdminCenterURL="https://crescent-admin.sharepoint.com"
$UserAccount="SPAdmin@crescent.com"
$PropertyName="SPS-Skills"
$PropertyValues = New-Object "System.Collections.Generic.List``1[System.string]"
$PropertyValues.Add("SharePoint")
$PropertyValues.Add("PowerShell")
$PropertyValues.Add("C#")

#Call the function
Update-MultiUserProfileProperty -AdminCenterURL $AdminCenterURL -UserAccount $UserAccount -PropertyName $PropertyName -PropertyValues $PropertyValues

How to Add a Custom Tile to SharePoint 2016 App Launcher

$
0
0
Requirement: Add new tile to App Launcher in SharePoint Online.

How to Add a Custom Tile to SharePoint 2016 App Launcher?
We wanted to place a new tile in SharePoint 2016 app launcher for support center site, as an end-user usability improvement. SharePoint 2016 Feature Pack 1 brought us the capability to add new tile to app launcher. Here is how you can customize SharePoint 2016 App launcher.

Step 1: Enable the "Custom Tiles" feature in SharePoint 2016 with PowerShell:
Use this PowerShell script to enable custom tiles feature. 
Enable-SPFeature -Identity CustomTiles -Url "http://intranet.crescent.com" -Force
This creates a new list "Custom Tiles" in the given web application's root site collection.

Step 2: Create new Tile in "Custom Tiles" list
Once the feature is activated, navigate to: http://intranet.crescent.com/Lists/Custom%20Tiles/AllItems.aspx URL and add a new entry with desired URL and image for tile for your custom tile. Please note, this list is hidden from browser interface, so you should use the link to directly in the browser to navigate to the list.sharepoint 2016 app launcher customize

It may take up to 24 hours for the new tile to reflect. Clear your browser cache, or open the browser in Private mode to see the new tile in action.
how to add custom tile in sharepoint 2016



SharePoint Online: Grant Permission to List Item using PowerShell

$
0
0
Permissions are hierarchical in SharePoint from Top Site collection till the List Item level. To set unique permissions on list items, you need to configure permissions on item level. Here is how:

How to Grant Access to Individual List Items in SharePoint Online?
Got a business requirement to grant permissions at List item level. To set explicit permissions on SharePoint online list items, we need to break the permission inheritance first (stop inheriting permissions) and then add user or group to the List Item.
  • Go to your SharePoint Online list or library >> Select the Item to which you want to provide unique permissions. 
  • Click on "Shared With" button from the ribbon. On the Shared With page, click Advanced.
    set item level permission in sharepoint online
  • On the Permissions tab, in the Inheritance group, click Stop Inheriting Permissions button. Confirm the prompt.
    sharepoint online list item permissions powershell
  • Now, from the ribbon, click on "Grant Permissions." button. In the Share dialog box, enter names, email addresses. Click the Show Options button. In the Select A Permission Level list box, select appropriate permission level such as Edit.
    powershell to grant permission to list item in sharepoint online
  • Click Share.
Having too many Item level permissions often leads to performance issues! so, be careful.

SharePoint Online: Set List Item Permissions using 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"

#To call non-generic method Load(list, x => x.HasUniqueRoleAssignments)
Function Invoke-LoadMethod() {
param(
[Microsoft.SharePoint.Client.ClientObject]$Object = $(throw "Please provide a Client Object"),
[string]$PropertyName
)
$ctx = $Object.Context
$load = [Microsoft.SharePoint.Client.ClientContext].GetMethod("Load")
$type = $Object.GetType()
$clientLoad = $load.MakeGenericMethod($type)

$Parameter = [System.Linq.Expressions.Expression]::Parameter(($type), $type.Name)
$Expression = [System.Linq.Expressions.Expression]::Lambda([System.Linq.Expressions.Expression]::Convert([System.Linq.Expressions.Expression]::PropertyOrField($Parameter,$PropertyName),[System.Object] ), $($Parameter))
$ExpressionArray = [System.Array]::CreateInstance($Expression.GetType(), 1)
$ExpressionArray.SetValue($Expression, 0)
$clientLoad.Invoke($ctx,@($Object,$ExpressionArray))
}

Function Set-ListItemPermission
{
param
(
[Parameter(Mandatory=$true)] [string]$SiteURL,
[Parameter(Mandatory=$true)] [string]$ListName,
[Parameter(Mandatory=$true)] [string]$ItemID,
[Parameter(Mandatory=$true)] [string]$PermissionLevel,
[Parameter(Mandatory=$true)] [string]$UserID
)
Try {
#Setup Credentials to connect
$Cred= Get-Credential
$Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)

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

#Get the List and Item
$List = $Ctx.Web.Lists.GetByTitle($ListName)
$ListItem=$List.GetItemByID($ItemID)
$Ctx.Load($List)
$Ctx.Load($ListItem)
$Ctx.ExecuteQuery()

#Check if Item has unique permission already
Invoke-LoadMethod -Object $list -PropertyName "HasUniqueRoleAssignments"
$Ctx.ExecuteQuery()

#Break Item's permision Inheritance, if its inheriting permissions from the parent
if (-not $ListItem.HasUniqueRoleAssignments)
{
$ListItem.BreakRoleInheritance($false, $false) #keep the existing permissions: No - Clear listitems permissions: No
$ctx.ExecuteQuery()
}

#Get the User
$User = $Ctx.Web.EnsureUser($UserID)
$Ctx.load($User)
$Ctx.ExecuteQuery()

#Get the role
$Role = $Ctx.web.RoleDefinitions.GetByName($PermissionLevel)
$RoleDB = New-Object Microsoft.SharePoint.Client.RoleDefinitionBindingCollection($Ctx)
$RoleDB.Add($Role)

#Assign permissions
$UserPermissions = $ListItem.RoleAssignments.Add($User,$RoleDB)
$ListItem.Update()
$Ctx.ExecuteQuery()

Write-host -f Green "Permission granted to List Item successfully!"
}
Catch {
Write-host -f Red "Error granting permission to List Item!" $_.Exception.Message
}
}

#Set parameter values
$SiteURL="https://crescent.sharepoint.com"
$ListName="Projects"
$ItemID="1"
$UserID="salaudeen@crescent.com"
$PermissionLevel="Edit"

#Call the function
Set-ListItemPermission -SiteURL $SiteURL -ListName $ListName -ItemID $ItemID -UserID $UserID -PermissionLevel $PermissionLevel

This script grants permission on Item level for given user. If you want to provide permission to SharePoint Group, Instead of line
$User = $Web.EnsureUser($UserAccount)
#use:
$Group =$Web.SiteGroups.GetByName($GroupName)
#and then
$GroupPermissions = $Item.RoleAssignments.Add($Group,$RoleDB)

How to Disable Quick Edit in SharePoint?

$
0
0
Requirement:  Disable quick edit in SharePoint 2016 list.

How to disable quick edit in sharepoint 2013 or SharePoint 2016?
Bit background: We've a project tracking list with field "Project Health" which is updated by an event receiver based on certain parameters and business logic. So, we made the field hidden in SharePoint online using: SharePoint Online: How to Hide a Column from NewForm/EditForm?

Now the problem is: users can go to "Quick Edit" mode of the list and they get hidden field there! Although the column was hidden from Edit and New Forms, SharePoint quick edit (which replaced Datasheet view in previous versions of SharePoint) still displays the hidden field and we decided to disable quick edit mode for the SharePoint list.

SharePoint how to disable quick edit:
To disable quick edit mode in SharePoint 2013/2016 or in SharePoint online,
  • Go to the list settings >> Click on "Advanced settings" link
  • In Advanced Settings link, Scroll down and Under "Quick property editing " option, choose "No" for "Allow items in this list to be edited using Quick Edit?" and then click OK.
    sharepoint 2013 disable quick edit powershell
  • This disables quick edit in SharePoint list.

Disable quick edit using PowerShell
Here is how we can disable quick edit sharepoint 2013 programmatically with PowerShell.
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Parameters
$WebURL="http://intranet.crescent.com"
$ListName="Projects"

#Get Web and List objects
$Web = Get-SPWeb $WebURL
$List = $Web.Lists.TryGetList($ListName)

$List.DisableGridEditing=$true
$List.Update()

CSOM to disable quick edit in SharePoint online: Unfortunately, this property is not exposed in SharePoint CSOM. So, you can't disable quick edit using CSOM. As a workaround you can hide the quick edit button with CSS (or create a list, disable quick edit using above UI method, save the list as template, and then create a new list instance from the template).
how to disable quick edit in sharepoint 2013

CSS to disable quick edit in SharePoint Online  
Alternatively, you can hide Quick Edit button in the ribbon with CSS also. Here is the CSS to hide sharepoint quick edit:
<style>
#Ribbon\.List\.ViewFormat\.Datasheet-Large {
display:none;
}
</style>
Click on Settings Gear >> Edit Page >> Click on "Add Web Part " link and then Add script editor web part. Edit snippet and Place this CSS code in it, Stop Editing to save your changes. For Libraries, use: #Ribbon\.Library\.ViewFormat\.Datasheet-Large

Explorer View in SharePoint Online

$
0
0
SharePoint Online Explorer view provides great flexibility like Windows Explorer functionality to manage Files and folders. Majority of the usage: drag and drop!

Where is Explorer View in SharePoint Online?
Explorer view in SharePoint online modern UI is moved under View section! To enable explorer view in sharepoint online,
  • Click on the View menu drop down from top-right area ( such as "All Documents")  >> Select "View in File Explorer" Menu item. >> This opens the document library in explorer view for SharePoint Online.
explorer view in sharepoint online

SharePoint Online explorer view not working? or Greyed out?
Explorer view is available only on 32 bit version of Internet Explorer! You cannot open in explorer view on Google Chrome or Microsoft Edge browsers.

Now SharePoint Online modern document libraries also provides drag and drop functionalities. E.g.
  • You can do multiple file upload with drag and drop
  • Create folders and drag and drop files to it with in browser itself. (You can't drag and drop a folder however!). 
  • You can copy/move files within the SharePoint Online libraries using Modern document library user interface.
Tags: sharepoint online explorer view not working, sharepoint online view in windows explorer, sharepoint online open in explorer view, using explorer view in sharepoint online, sharepoint online explorer view greyed out, sharepoint online cannot open in explorer view

SharePoint Online: How to Enable Versioning on a Document Library using PowerShell

$
0
0
What is versioning in SharePoint Online?
Version history feature in SharePoint Online tracks every change to the document and creates a copy of it when someone changes a document. Each version of the document has the following:
  • Version No
  • When the version was created
  • Who made the version (change)
  • Size of the version
Once the versioning feature is enabled, you can view/restore the previous versions of the document.

How to Enable Version History in SharePoint Online Document Library?
To Enable or Disable Versioning in SharePoint Online Document Library:
  • Navigate to your document library >> Click on Settings gear >> and then "Library Settings" Menu item.
  • Under Library settings page, Click on "Versioning Settings"
  • Select "Create major versions" option and enter number of versions to track (by default, this is enabled with 500 versions in SharePoint Online). sharepoint online powershell to enable versioning in document library
  • Scroll to the bottom of the page. Click "OK" to apply versioning setting changes.

SharePoint Online: PowerShell to enable versioning in document library
#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 Enable-DocLibraryVersioning()
{
param
(
[Parameter(Mandatory=$true)] [string] $SiteURL,
[Parameter(Mandatory=$true)] [string] $DocLibraryName
)
Try {
#Setup Credentials to connect
$Cred = Get-Credential
$Cred = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.UserName,$Cred.Password)

#Get the Library from the web
$Library = $Ctx.Web.Lists.GetByTitle($DocLibraryName)

#enable versioning in sharepoint online
$Library.EnableVersioning = $True
$Library.MajorVersionLimit = 50

$Library.update()
$Ctx.ExecuteQuery()

write-host -f Green "Version History Enabled for Document Library!"
}
Catch {
write-host -f Red "Error enabling versioning in Document Library!" $_.Exception.Message
}
}

#Set Parameters
$SiteURL= "https://crescent.sharepoint.com/"
$DocLibraryName="Project Docs"

#Call the function to enable versioning in document library
Enable-DocLibraryVersioning -siteURL $SiteURL -DocLibraryName $DocLibraryName

To Enable version history on all lists and libraries, use: 
SharePoint Online: Enable Versioning on All List and Libraries using PowerShell

SharePoint Online: Copy List Items from One List to Another using PowerShell

$
0
0
Requirement:  Copy List items to another list in SharePoint Online

How to copy list items to another list in SharePoint Online? 
Use Quick Edit (Datasheet view) to copy-paste list items between lists in SharePoint online. Make sure you have matching columns and column order is same in both views.
copy list items to another list sharepoint online



SharePoint Online: Copy List Item to Another List using 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 Copy-ListItems()
{
param
(
[Parameter(Mandatory=$true)] [string] $SiteURL,
[Parameter(Mandatory=$true)] [string] $SourceListName,
[Parameter(Mandatory=$true)] [string] $TargetListName
)
Try {
#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 Source List and Target Lists
$SourceList = $Ctx.Web.Lists.GetByTitle($SourceListName)
$TargetList = $Ctx.Web.Lists.GetByTitle($TargetListName)

#Get All Items from Source List
$SourceListItems = $SourceList.GetItems([Microsoft.SharePoint.Client.CamlQuery]::CreateAllItemsQuery())
$Ctx.Load($SourceListItems)
$Ctx.ExecuteQuery()

#Get each column value from source list and add them to target
ForEach($SourceItem in $SourceListItems)
{
$NewItem =New-Object Microsoft.SharePoint.Client.ListItemCreationInformation
$ListItem = $TargetList.AddItem($NewItem)

#Map each field from source list to target list - INTERNAL NAMES
$ListItem["Title"] = $SourceItem["Title"]
$ListItem["IsActive"] = $SourceItem["IsActive"]
$ListItem["ProjectStartDate"] = $SourceItem["ProjectStartDate"]
$ListItem["Department"] = $SourceItem["Department"]
$ListItem["Priority"] = $SourceItem["Priority"]
$ListItem.update()
}
$Ctx.ExecuteQuery()

write-host -f Green "Total List Items Copied from '$SourceListName' to '$TargetListName' : $($SourceListItems.count)"
}
Catch {
write-host -f Red "Error Copying List Items!" $_.Exception.Message
}
}

#Set Parameters
$SiteURL= "https://crescent.sharepoint.com/"
$SourceListName="Projects Template"
$TargetListName="Project Innovate"

#Call the function to copy list items
Copy-ListItems -siteURL $SiteURL -SourceListName $SourceListName -TargetListName $TargetListName
This script copies all mapped column values from the source to the target list. Lets enhance the script bit to automatically copy all columns matching from the source to target list.

SharePoint Online: Copy List items using 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 Copy-ListItems()
{
param
(
[Parameter(Mandatory=$true)] [string] $SiteURL,
[Parameter(Mandatory=$true)] [string] $SourceListName,
[Parameter(Mandatory=$true)] [string] $TargetListName
)
Try {
#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 Source List and Target Lists
$SourceList = $Ctx.Web.Lists.GetByTitle($SourceListName)
$TargetList = $Ctx.Web.Lists.GetByTitle($TargetListName)

#Get All Items from Source List
$SourceListItems = $SourceList.GetItems([Microsoft.SharePoint.Client.CamlQuery]::CreateAllItemsQuery())
$Ctx.Load($SourceListItems)
$Ctx.ExecuteQuery()

#Get All fields from Source List & Target List
$SourceListFields = $SourceList.Fields
$Ctx.Load($SourceListFields)
$TargetListFields = $TargetList.Fields
$Ctx.Load($TargetListFields)
$Ctx.ExecuteQuery()

#Get each column value from source list and add them to target
ForEach($SourceItem in $SourceListItems)
{
$NewItem =New-Object Microsoft.SharePoint.Client.ListItemCreationInformation
$ListItem = $TargetList.AddItem($NewItem)

#Map each field from source list to target list
Foreach($SourceField in $SourceListFields)
{
#Skip Read only, hidden fields, content type and attachments
If((-Not ($SourceField.ReadOnlyField)) -and (-Not ($SourceField.Hidden)) -and ($SourceField.InternalName -ne "ContentType") -and ($SourceField.InternalName -ne "Attachments") )
{
$TargetField = $TargetListFields | where { $_.Internalname -eq $SourceField.Internalname}
if($TargetField -ne $null)
{
#Copy column value from source to target
$ListItem[$TargetField.InternalName] = $SourceItem[$SourceField.InternalName]
}
}
}
$ListItem.update()
$Ctx.ExecuteQuery()
}

write-host -f Green "Total List Items Copied from '$SourceListName' to '$TargetListName' : $($SourceListItems.count)"
}
Catch {
write-host -f Red "Error Copying List Items!" $_.Exception.Message
}
}

#Set Parameters
$SiteURL= "https://crescent.sharepoint.com/"
$SourceListName="Projects Template"
$TargetListName="Project Innovate"

#Call the function to copy list items
Copy-ListItems -siteURL $SiteURL -SourceListName $SourceListName -TargetListName $TargetListName

Here is my another post for SharePoint On-premises to copy list item: Copy SharePoint List Item to Another List using PowerShell

SharePoint Online: Download Attachments from List using PowerShell

$
0
0
Requirement: Download attachments from SharePoint Online List

PowerShell to download attachments from a List Item:
Lets download SharePoint list item attachment programmaticallyfrom a particular list item.
#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 Download-ListItemAttachments()
{
param
(
[Parameter(Mandatory=$true)] [string] $SiteURL,
[Parameter(Mandatory=$true)] [string] $ListName,
[Parameter(Mandatory=$true)] [string] $ListItemID,
[Parameter(Mandatory=$true)] [string] $DownloadPath
)
Try {
#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 List Item
$List = $Ctx.Web.Lists.GetByTitle($ListName)
$ListItem= $List.GetItemByID($ListItemID)

#Get All attachments from the List Item
$AttachmentsColl = $ListItem.AttachmentFiles
$Ctx.Load($AttachmentsColl)
$Ctx.ExecuteQuery()

#Get each attachment
ForEach($Attachment in $AttachmentsColl)
{
#Download attachment
$FileContent = [Microsoft.SharePoint.Client.File]::OpenBinaryDirect($Ctx, $Attachment.ServerRelativeUrl)
$FileStream = [System.IO.File]::Create($DownloadPath+$Attachment.FileName)
$FileContent.Stream.CopyTo($FileStream)
$FileStream.Close()
}

write-host -f Green "Total List Attachments Downloaded : $($AttachmentsColl.count)"
}
Catch {
write-host -f Red "Error Downloading List Item Attachments!" $_.Exception.Message
}
}

#Set Parameters
$SiteURL= "https://crescent.sharepoint.com/"
$ListName="Projects"
$ListItemID="1"
$DownloadPath="C:\Temp\"

#Call the function to copy list items
Download-ListItemAttachments -SiteURL $SiteURL -ListName $ListName -ListItemID $ListItemID -DownloadPath $DownloadPath

Download Attachments from All Items in the List using PowerShell:
Here is the PowerShell to download SharePoint Online list attachments from all items.
#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 Download-ListAttachments()
{
param
(
[Parameter(Mandatory=$true)] [string] $SiteURL,
[Parameter(Mandatory=$true)] [string] $ListName,
[Parameter(Mandatory=$true)] [string] $DownloadDirectory
)
Try {
#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 All Items from the List
$List = $Ctx.Web.Lists.GetByTitle($ListName)
$ListItems = $List.GetItems([Microsoft.SharePoint.Client.CamlQuery]::CreateAllItemsQuery())
$Ctx.Load($ListItems)
$Ctx.ExecuteQuery()

#Create download directory if it doesn't exist
If (!(Test-Path -path $DownloadDirectory))
{
New-Item $DownloadDirectory -type directory
}

#Iterate through each list item
Foreach($Item in $ListItems)
{
#Get All attachments from the List Item
$AttachmentsColl = $Item.AttachmentFiles
$Ctx.Load($AttachmentsColl)
$Ctx.ExecuteQuery()

#Get attachment for each list item
ForEach($Attachment in $AttachmentsColl)
{
#Download attachment
$FileContent = [Microsoft.SharePoint.Client.File]::OpenBinaryDirect($Ctx, $Attachment.ServerRelativeUrl)
$FileName= $DownloadDirectory+$Item.id.ToString()+"_"+$Attachment.FileName
$FileStream = [System.IO.File]::Create($FileName)
$FileContent.Stream.CopyTo($FileStream)
$FileStream.Close()
}
}

write-host -f Green "List Attachments Downloaded Successfully!"
}
Catch {
write-host -f Red "Error Downloading List Attachments!" $_.Exception.Message
}
}

#Set Parameters
$SiteURL= "https://crescent.sharepoint.com/"
$ListName="Projects"
$DownloadDirectory="C:\Temp\"

#Call the function to copy list items
Download-ListAttachments -SiteURL $SiteURL -ListName $ListName -DownloadDirectory $DownloadDirectory

SharePoint Online: Add Attachment to List Item using PowerShell

$
0
0
Requirement: Add Attachment to SharePoint Online List Item

PowerShell to Add an Attachment to List Item:
#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 Add-AttachmentToListItem()
{
param
(
[Parameter(Mandatory=$true)] [string] $SiteURL,
[Parameter(Mandatory=$true)] [string] $ListName,
[Parameter(Mandatory=$true)] [string] $ItemID,
[Parameter(Mandatory=$false)] [string] $AttachmentPath
)
Try {
#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 List & List Item
$List = $Ctx.Web.Lists.GetByTitle($ListName)
$Ctx.Load($List)
$ListItem = $List.GetItemByID($ItemID)
$Ctx.Load($ListItem)
$Ctx.ExecuteQuery()

#Get All existing attachments
$AttachmentFiles = $ListItem.AttachmentFiles
$Ctx.Load($AttachmentFiles)
$Ctx.ExecuteQuery()

#Check if attachment file name exists already
$FileName = Split-Path $AttachmentPath -Leaf
$AttachmentFile = $AttachmentFiles | where { ($_.FileName -eq $FileName) }
If($AttachmentFile -eq $Null)
{
#Get the Attachment file from local disk
[Byte[]]$Bytes = [System.IO.File]::ReadAllBytes($AttachmentPath)
$ContentStream = New-Object -TypeName System.IO.MemoryStream -ArgumentList @(,$Bytes)

#Create Attachment object
$AttachmentCreation = New-Object Microsoft.SharePoint.Client.AttachmentCreationInformation
$AttachmentCreation.ContentStream = $ContentStream
$AttachmentCreation.FileName = $FileName
[Void]$ListItem.AttachmentFiles.Add($AttachmentCreation)
$Ctx.ExecuteQuery()

write-host -f Green "Attachment Added to List Item!"
}
else
{
write-host -f Yellow "Attachment File Name Exists already!"
}
}
Catch {
write-host -f Red "Error Adding Attachment to List!" $_.Exception.Message
}
}

#Set Parameters
$SiteURL= "https://crescent.sharepoint.com/"
$ListName="Projects"
$ItemID="5"
$AttachmentPath="C:\Projects\Proposal.docx"

#Call the function to copy list items
Add-AttachmentToListItem -SiteURL $SiteURL -ListName $ListName -ItemID $ItemID -AttachmentPath $AttachmentPath

SharePoint Online: Delete Attachments from List Item using Powershell

$
0
0
Requirement: Delete Attachment from SharePoint Online List Item.

PowerShell to Remove Attachment from SharePoint Online List Item:
#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 Remove-AttachmentFromListItem()
{
param
(
[Parameter(Mandatory=$true)] [string] $SiteURL,
[Parameter(Mandatory=$true)] [string] $ListName,
[Parameter(Mandatory=$true)] [string] $ItemID,
[Parameter(Mandatory=$false)] [string] $AttachmentFileName
)
Try {
#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 List & List Item
$List = $Ctx.Web.Lists.GetByTitle($ListName)
$Ctx.Load($List)
$ListItem = $List.GetItemByID($ItemID)
$Ctx.Load($ListItem)
$Ctx.ExecuteQuery()

#Get All existing attachments
$AttachmentFiles = $ListItem.AttachmentFiles
$Ctx.Load($AttachmentFiles)
$Ctx.ExecuteQuery()

#Check if attachment file name exists
$AttachmentFile = $AttachmentFiles | where { ($_.FileName -eq $AttachmentFileName) }
If($AttachmentFile -ne $Null)
{
$AttachmentFile.DeleteObject()
$Ctx.ExecuteQuery()

write-host -f Green "Attachment File '$AttachmentFileName' Removed from List Item!"
}
else
{
write-host -f Yellow "Attachment File '$AttachmentFileName' Doesn't Exist!"
}
}
Catch {
write-host -f Red "Error Removing Attachment From List!" $_.Exception.Message
}
}

#Set Parameters
$SiteURL= "https://crescent.sharepoint.com/"
$ListName="Projects"
$ItemID="64"
$AttachmentFileName="ProjectProposal.docx"

#Call the function to copy list items
Remove-AttachmentFromListItem -SiteURL $SiteURL -ListName $ListName -ItemID $ItemID -AttachmentFileName $AttachmentFileName

SharePoint Online: Get All List Fields using PowerShell

$
0
0
Requirement: SharePoint Online PowerShell to Get All List Fields.

How to Get List Fields in SharePoint Online?
If you navigate to list settings, under "Columns" section, you'll find all fields of the particular list.
sharepoint Online get all list fields

SharePoint Online: PowerShell to Get All List Fields
Lets use PowerShell to get list field names and internal names.

#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 parameter values
$SiteURL="https://crescent.sharepoint.com"
$ListName="Projects"

#$Cred= Get-Credential
$Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)

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

#Get the List and list fields
$List = $Ctx.Web.Lists.GetByTitle($ListName)
$Ctx.Load($List)
$Ctx.Load($List.Fields)
$Ctx.ExecuteQuery()

#Iterate through each field in the list
Foreach ($Field in $List.Fields)
{
#Skip System Fields
if(($Field.ReadOnlyField -eq $False) -and ($Field.Hidden -eq $False))
{
Write-Host $Field.Title : $Field.InternalName
}
}

SharePoint Online: Get All Fields of a List and Export to CSV
Lets get all list fieldsand export them to a CSV file.
#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 Get all fields from a SharePoint Online list or library
Function Get-ListFields()
{
param
(
[Parameter(Mandatory=$true)] [string] $SiteURL,
[Parameter(Mandatory=$true)] [string] $ListName
)

Try {
$Cred= Get-Credential
$Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)

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

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

#Array to hold result
$FieldData = @()
#Iterate through each field in the list
Foreach ($Field in $List.Fields)
{
Write-Host $Field.Title `t $Field.Description `t $Field.InternalName `t $Field.Id `t $Field.TypeDisplayName

#Send Data to object array
$FieldData += New-Object PSObject -Property @{
'Field Title' = $Field.Title
'Field Description' = $Field.Description
'Field ID' = $Field.Id
'Internal Name' = $Field.InternalName
'Type' = $Field.TypeDisplayName
'Schema' = $Field.SchemaXML
}
}
Return $FieldData
}
Catch {
write-host -f Red "Error Getting Fields from List!" $_.Exception.Message
}
}

#Set parameter values
$SiteURL="https://crescent.sharepoint.com"
$ListName="Projects"
$CSVLocation ="C:\Temp\ListFields.csv"

#Call the function to get all list fields
Get-ListFields -SiteURL $SiteURL -ListName $ListName | Export-Csv $CSVLocation -NoTypeInformation

SharePoint Online: Copy File between Document Libraries using PowerShell

$
0
0
How to Copy a File in SharePoint Online Document Library?
  • Navigate to your SharePoint Online document library. Right click on the file to copy >> Select "Copy To" menu item
    sharepoint online copy document
  • This opens information panel in the right. Select the target library to which your needs to be copied. You can select current library, any other library in the current site or even a library in any different site collection.
    sharepoint online copy file
  • Pick the library and click on "Copy Here" button to start copying the file.
  • You'll see the "Copying" message in tool bar and your fill will be copied momentarily.
    sharepoint online powershell copy documents
SharePoint Online: PowerShell to Copy Documents
Here is the PowerShell to copy files in SharePoint Online document library.
Function Copy-File
{
param
(
[Parameter(Mandatory=$true)] [string] $SiteURL,
[Parameter(Mandatory=$true)] [string] $SourceFileURL,
[Parameter(Mandatory=$true)] [string] $TargetFileURL
)
Try {
$Cred= Get-Credential
$Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)

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

#Get the source file
$SourceFile =$Ctx.Web.GetFileByServerRelativeUrl($SourceFileURL)
$Ctx.Load($SourceFile)
$Ctx.ExecuteQuery()

#Copy File to destination
$SourceFile.CopyTo($TargetFileURL, $True)
$Ctx.ExecuteQuery()

Write-Host "File Copied from '$SourceFileURL' to '$TargetFileURL'" -F Green
}
Catch {
write-host -f Red "Error Copying File!" $_.Exception.Message
}
}

#Set Parameter values
$SiteURL="https://crescent.sharepoint.com/"
$SourceFileURL="/Project Documents/Active Users.xlsx"
$TargetFileURL="/Project Documents/Active Users2.xlsx"

#Call the function
Copy-File -SiteURL $SiteURL -SourceFileURL $SourceFileURL -TargetFileURL $TargetFileURL
This method copies given document either to same document library or different document library with in the same site along with its metadata fields (Except: Created by and Modified by fields - and obviously, the columns should exists in both libraries)!

SharePoint Online: Copy Files Between Site Collections using PowerShell

$
0
0
Requirement: SharePoint Online Copy Files between Site Collections in document libraries.

PowerShell to Copy Files between Site Collections in SharePoint Online:
Lets copy a single from source to destination.
#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 parameter values
$SourceSiteURL="https://crescent.sharePoint.com/sites/sales"
$TargetSiteURL="https://abraaj.sharepoint.com/sites/Ops/"

#Set Source and Destination File URLs - Relative path
$SourceFileURL="/Sites/Sales/Project Documents/Active Users.xlsx"
$TargetFileURL="/Sites/Ops/Shared Documents/Active Users.xlsx"

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

#Setup the contexts
$SourceCtx = New-Object Microsoft.SharePoint.Client.ClientContext($SourceSiteURL)
$SourceCtx.Credentials = $Credentials
$TargetCtx = New-Object Microsoft.SharePoint.Client.ClientContext($TargetSiteURL)
$TargetCtx.Credentials = $Credentials

#Get the Source File
$FileInfo = [Microsoft.SharePoint.Client.File]::OpenBinaryDirect($SourceCtx, $SourceFileURL)

#Copy File to the Target location
[Microsoft.SharePoint.Client.File]::SaveBinaryDirect($TargetCtx, $TargetFileURL, $FileInfo.Stream,$True)

This script simply copies a particular file from source site/site collection to the target site/site collection.

Copy All Files and Folder from One Library to Another Library between different Site Collections:
#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 Copy-Files
{
param
(
[Parameter(Mandatory=$true)] [Microsoft.SharePoint.Client.Folder] $SourceFolder,
[Parameter(Mandatory=$true)] [Microsoft.SharePoint.Client.Folder] $TargetFolder
)
Try {
#Get all Files from the source folder
$SourceFilesColl = $SourceFolder.Files
$SourceFolder.Context.Load($SourceFilesColl)
$SourceFolder.Context.ExecuteQuery()

#Iterate through each file and copy
Foreach($SourceFile in $SourceFilesColl)
{
#Get the source file
$FileInfo = [Microsoft.SharePoint.Client.File]::OpenBinaryDirect($SourceFolder.Context, $SourceFile.ServerRelativeUrl)

#Copy File to the Target location
$TargetFileURL = $TargetFolder.ServerRelativeUrl+"/"+$SourceFile.Name
[Microsoft.SharePoint.Client.File]::SaveBinaryDirect($TargetFolder.Context, $TargetFileURL, $FileInfo.Stream,$True)

Write-host -f Green "Copied File '$($SourceFile.ServerRelativeUrl)' to '$TargetFileURL'"
}

#Process Sub Folders
$SubFolders = $SourceFolder.Folders
$SourceFolder.Context.Load($SubFolders)
$SourceFolder.Context.ExecuteQuery()
Foreach($SubFolder in $SubFolders)
{
If($SubFolder.Name -ne "Forms")
{
#Prepare Target Folder
$TargetFolderURL = $SubFolder.ServerRelativeUrl -replace $SourceLibrary.RootFolder.ServerRelativeUrl, $TargetLibrary.RootFolder.ServerRelativeUrl
Try {
$Folder=$TargetFolder.Context.web.GetFolderByServerRelativeUrl($TargetFolderURL)
$TargetFolder.Context.load($Folder)
$TargetFolder.Context.ExecuteQuery()
}
catch {
#Create Folder
if(!$Folder.Exists)
{
$TargetFolderURL
$Folder=$TargetFolder.Context.web.Folders.Add($TargetFolderURL)
$TargetFolder.Context.Load($Folder)
$TargetFolder.Context.ExecuteQuery()
Write-host "Folder Added:"$SubFolder.Name -f Yellow
}
}
#Call the function recursively
Copy-Files -SourceFolder $SubFolder -TargetFolder $Folder
}
}
}
Catch {
write-host -f Red "Error Copying File!" $_.Exception.Message
}
}

#Set Parameter values
$SourceSiteURL="https://crescent.sharePoint.com/sites/sales"
$TargetSiteURL="https://crescent.sharepoint.com/sites/ops"

$SourceLibraryName="Project Documents"
$TargetLibraryName="Documents"

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

#Setup the contexts
$SourceCtx = New-Object Microsoft.SharePoint.Client.ClientContext($SourceSiteURL)
$SourceCtx.Credentials = $Credentials
$TargetCtx = New-Object Microsoft.SharePoint.Client.ClientContext($TargetSiteURL)
$TargetCtx.Credentials = $Credentials

#Get the source library and Target Libraries
$SourceLibrary = $SourceCtx.Web.Lists.GetByTitle($SourceLibraryName)
$SourceCtx.Load($SourceLibrary)
$SourceCtx.Load($SourceLibrary.RootFolder)

$TargetLibrary = $TargetCtx.Web.Lists.GetByTitle($TargetLibraryName)
$TargetCtx.Load($TargetLibrary)
$TargetCtx.Load($TargetLibrary.RootFolder)
$TargetCtx.ExecuteQuery()

#Call the function
Copy-Files -SourceFolder $SourceLibrary.RootFolder -TargetFolder $TargetLibrary.RootFolder

Copy All Files from One Library to Another Library along with Metadata values:
This script copies all files and folders between document libraries in different site collections, preserving metadata field values such as: Created by, Modified By, Created At, Modified At, etc.
#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 Copy-AllFilesWithMetadata
{
param
(
[Parameter(Mandatory=$true)] [Microsoft.SharePoint.Client.Folder] $SourceFolder,
[Parameter(Mandatory=$true)] [Microsoft.SharePoint.Client.Folder] $TargetFolder
)
Try {
#Get all Files from the source folder
$SourceFilesColl = $SourceFolder.Files
$SourceFolder.Context.Load($SourceFilesColl)
$SourceFolder.Context.ExecuteQuery()

#Iterate through each file and copy
Foreach($SourceFile in $SourceFilesColl)
{
#Get the source file
$FileInfo = [Microsoft.SharePoint.Client.File]::OpenBinaryDirect($SourceFolder.Context, $SourceFile.ServerRelativeUrl)

#Copy File to the Target location
$TargetFileURL = $TargetFolder.ServerRelativeUrl+"/"+$SourceFile.Name
[Microsoft.SharePoint.Client.File]::SaveBinaryDirect($TargetFolder.Context, $TargetFileURL, $FileInfo.Stream,$True)

#Copy Metadata field values
$SourceListItem = $SourceFile.ListItemAllFields
$SourceFolder.Context.Load($SourceListItem)
$SourceFolder.Context.ExecuteQuery()

#Get the new file created
$TargetFile = $TargetFolder.Context.Web.GetFileByServerRelativeUrl($TargetFileURL)
$TargetListItem = $TargetFile.ListItemAllFields

#Set Metadata values from the source
$Author =$TargetFolder.Context.web.EnsureUser($SourceListItem["Author"].Email)
$TargetListItem["Author"] = $Author
$Editor =$TargetFolder.Context.web.EnsureUser($SourceListItem["Editor"].Email)
$TargetListItem["Editor"] = $Editor
$TargetListItem["Created"] = $SourceListItem["Created"]
$TargetListItem["Modified"] = $SourceListItem["Modified"]
$TargetListItem.Update()
$TargetFolder.Context.ExecuteQuery()

Write-host -f Green "Copied File '$($SourceFile.ServerRelativeUrl)' to '$TargetFileURL'"
}

#Process Sub Folders
$SubFolders = $SourceFolder.Folders
$SourceFolder.Context.Load($SubFolders)
$SourceFolder.Context.ExecuteQuery()
Foreach($SubFolder in $SubFolders)
{
If($SubFolder.Name -ne "Forms")
{
#Prepare Target Folder
$TargetFolderURL = $SubFolder.ServerRelativeUrl -replace $SourceLibrary.RootFolder.ServerRelativeUrl, $TargetLibrary.RootFolder.ServerRelativeUrl
Try {
$Folder=$TargetFolder.Context.web.GetFolderByServerRelativeUrl($TargetFolderURL)
$TargetFolder.Context.load($Folder)
$TargetFolder.Context.ExecuteQuery()
}
catch {
#Create Folder
if(!$Folder.Exists)
{
$TargetFolderURL
$Folder=$TargetFolder.Context.web.Folders.Add($TargetFolderURL)
$TargetFolder.Context.Load($Folder)
$TargetFolder.Context.ExecuteQuery()
Write-host "Folder Added:"$SubFolder.Name -f Yellow
}
}
#Call the function recursively
Copy-AllFilesWithMetadata -SourceFolder $SubFolder -TargetFolder $Folder
}
}
}
Catch {
write-host -f Red "Error Copying File!" $_.Exception.Message
}
}

#Set Parameter values
$SourceSiteURL="https://crescent.sharepoint.com/sites/sales"
$TargetSiteURL="https://crescent.sharepoint.com/sites/Ops"

$SourceLibraryName="Project Documents"
$TargetLibraryName="Documents"

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

#Setup the contexts
$SourceCtx = New-Object Microsoft.SharePoint.Client.ClientContext($SourceSiteURL)
$SourceCtx.Credentials = $Credentials
$TargetCtx = New-Object Microsoft.SharePoint.Client.ClientContext($TargetSiteURL)
$TargetCtx.Credentials = $Credentials

#Get the source library and Target Libraries
$SourceLibrary = $SourceCtx.Web.Lists.GetByTitle($SourceLibraryName)
$SourceCtx.Load($SourceLibrary)
$SourceCtx.Load($SourceLibrary.RootFolder)

$TargetLibrary = $TargetCtx.Web.Lists.GetByTitle($TargetLibraryName)
$TargetCtx.Load($TargetLibrary)
$TargetCtx.Load($TargetLibrary.RootFolder)
$TargetCtx.ExecuteQuery()

#Call the function
Copy-AllFilesWithMetadata -SourceFolder $SourceLibrary.RootFolder -TargetFolder $TargetLibrary.RootFolder

SharePoint Online: Get List Items from Folder using PowerShell

$
0
0
Requirement: Get list items from a folder in SharePoint Online.

SharePoint Online: PowerShell to Get List Items in a Folder
#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 Get-ListItemsFromFolder()
{
param
(
[Parameter(Mandatory=$true)] [string] $SiteURL,
[Parameter(Mandatory=$true)] [string] $ListName,
[Parameter(Mandatory=$true)] [string] $FolderURL
)
Try {
#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 list
$List=$Ctx.Web.Lists.GetByTitle($ListName)

#Frame CamlQuery to retrieve the items from the Folder
$CAMLQuery= New-Object Microsoft.SharePoint.Client.CamlQuery
#Set relative URL of the folder
$CAMLQuery.FolderServerRelativeUrl=$FolderURL

#Get List Items from the Folder
$ListItems=$List.GetItems($CAMLQuery)
$Ctx.Load($ListItems)
$Ctx.ExecuteQuery()

Write-host "Total Number of Items Found:"$ListItems.Count

#Iterate through all list items
Foreach($Item in $ListItems)
{
#Get Ids for each Item
Write-Host $item["ID"]
}
}
Catch {
write-host -f Red "Error Getting List Items from Folder!" $_.Exception.Message
}
}

#Set Parameter Values
$SiteURL="https://crescent.sharepoint.com"
$ListName="Projects"

#Relative URL to the Folder - For Libraries, E.g: "/Documents/2018" or "/sites/sales/documents/projects/active"
$FolderURL="/Lists/Projects/Active"

#Call the function to get list items from folder
Get-ListItemsFromFolder -SiteURL $SiteURL -ListName $ListName -FolderURL $FolderURL


PowerShell to Get Files from Folder in SharePoint Online:
This time, lets retrieve all files from a given folder in SharePoint Online document library using 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 Get-FilesFromFolder()
{
param
(
[Parameter(Mandatory=$true)] [string] $SiteURL,
[Parameter(Mandatory=$true)] [string] $FolderURL
)
Try {
#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 Folder and Files
$Folder=$Ctx.Web.GetFolderByServerRelativeUrl($FolderURL)
$Ctx.Load($Folder)
$Ctx.Load($Folder.Files)
$Ctx.ExecuteQuery()

#Iterate through each File in the folder
Foreach($File in $Folder.Files)
{
#Get Name for each File
Write-Host $File.Name
}
}
Catch {
write-host -f Red "Error Getting Files from Folder!" $_.Exception.Message
}
}

#Set Parameter Values
$SiteURL="https://crescent.sharepoint.com"
#Relative URL to the Folder - For Lists: "/Lists/ListURL/FolderURL"
$FolderURL="/Shared Documents/Documentation"

#Call the function to get list items from folder
Get-ListItemsFromFolder -SiteURL $SiteURL -FolderURL $FolderURL

Tags: sharepoint online get all files from folder, sharepoint csom get folder items, sharepoint caml get items in folder, sharepoint online get all items in a folder, sharepoint online powershell get all items in folder, sharepoint client object model get folder items, sharepoint online get list items inside folder, get all items from sharepoint list folder, sharepoint powershell get items in folder, powershell sharepoint get files in folder

SharePoint Online: How to Change Home Page using PowerShell

$
0
0
Requirement:  SharePoint Online Set Home Page!

How to change home page in sharepoint online?
To set home page in SharePoint Online:
  • Navigate to Site Settings >> Click on "Welcome Page" link under "Look and Feel" group
    SharePoint Online Set Home Page
  • This takes you to the "Site Welcome Page" (/_layouts/15/AreaWelcomePage.aspx) where you can pick any existing page and set it as a welcome page or home page for your SharePoint Online site.
    sharepoint online powershell set home page
This changes welcome page in SharePoint Online.

SharePoint Online: Change home page using PowerShell
Here is the PowerShell to set the page as a homepage 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 Parameter Values
$SiteURL="https://crescent.sharepoint.com"
#Relative url of the homepage
$HomePageURL="SitePages/default.aspx"

#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

#Set welcome page
$Ctx.web.RootFolder.WelcomePage = $HomePageURL
$Ctx.web.RootFolder.Update()
$Ctx.ExecuteQuery()
This PowerShell CSOM script sets home page in SharePoint Online.

List View Threshold in SharePoint Online - FAQs

$
0
0
What is List View Threshold Limit in SharePoint Online?
List View Thresholdis a limit of 5000 list items in SharePoint online, which can't be exceeded!

Is it possible to Change List View Threshold in SharePoint Online?
No! we can't change list view threshold in SharePoint Online. The number 5000 is fixed and controlled by Microsoft to ensure better performance in SharePoint Online as its operates as shared tenant environment. If its SharePoint On-premises, You can change list threshold via Central Administration site: How to Increase List Threshold in SharePoint?

How to Increase List View Threshold in SharePoint Online?
Its not possible to increase threshold limit sharepoint online!

List View Lookup Threshold in SharePoint Online:
SharePoint Online has lookup column threshold of 12.(It was 8 in SharePoint on-premises - before June 2013 CU). Also, when the parent list contains more than 5000 items, then you'll get the error message: "This is a lookup column that displays data from another list that currently exceeds the List View Threshold defined by the administrator (5000)"

I've less than 8 Lookup columns, but still I'm getting Lookup threshold exceed error message. Why?
Well, other than standard lookup columns, there are few more columns in SharePoint which are considered as "Lookup"! Such as:
  • Managed metadata columns
  • Person or group columns
  • Workflow Status
  • Created by, Modified by
  •  Name ( linked to Document) , Link (Edit to edit item) , Name ( linked to Document with edit menu), type ( icon linked to document)
I've more than 5000 items in my SharePoint List. How Do I Overcome threshold Issue?
  • Set filters through "Modify list view" and limit the number of items in the view to less than 5000 to mitigate this issue. You can categorize your list items based on metadata whichever present in the list such as category, department, business function, etc.
  • Archive old list items either by moving to a new list or a folder inside the same list.
  • Try adding Indexed columns.
What's the problem when you Exceed List Threshold Limit?
When the list view threshold limit is exceeded, you'll find a warning message in list settings under as List View Threshold: The Number of items in this list exceeds the list view threshold, which is 5000 items. Tasks that cause excessive server load (such as those involving all list items) are currently prohibited." message.
list view threshold in sharepoint online
Also, when you try to filter or sort column values, you'll see "Cannot show the value of the filter. The field may not be filterable, or the number of items returned exceeds the list view threshold enforced by the administrator" message.
list view threshold sharepoint online

How to avoid list Threshold issue in CSOM?
The same threshold issue arises when you try to get all list items programmatically. Use "ListItemCollectionPosition" Property when you access large lists through CSOM code. Here is my example for reading large lists in SharePoint Online PowerShell-CSOM : How to Get All List Items from Large Lists in SharePoint Online

Here is the Microsoft article on managing large lists in SharePoint Online: Manage large lists and libraries in SharePoint
Viewing all 1058 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>