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

Import-Module: The specified module 'Microsoft.Online.SharePoint.Powershell' was not loaded because no valid module file was found in any module directory.

$
0
0
Problem:
When trying to add PowerShell module for SharePoint online, using "Import-Module Microsoft.Online.SharePoint.PowerShell", it resulted in below error in both PowerShell console and in PowerShell ISE.
"Import-Module : The specified module 'Microsoft.Online.SharePoint.Powershell' was not loaded because no valid module file was found in any module directory."
Import-Module-The specified module 'Microsoft.Online.SharePoint.Powershell' was not loaded because no valid module file was found in any module directory.

Solution: 
  • Make sure you have SharePoint Online Management Shell installed on the machine you are getting the error. You can download and install SharePoint Online Management Shell from: https://www.microsoft.com/en-us/download/details.aspx?id=35588
    download and install sharepoint online managment shell
    You can check installed modules by: Get-Module -listavailable
  • If you are getting this error in SharePoint Online Management Shell, Make sure you removed x86 version of SharePoint online management shell from your computer, and Try download and Re-Install 64bit version!
  • Try running: Set-ExecutionPolicy Unrestrict once
  • Run PowerShell or PowerShell ISE as a administrator

SharePoint Online: Get List in PowerShell

$
0
0
SharePoint Online: Get List from PowerShell
Here is the PowerShell to Get SharePoint Online List

Import-Module Microsoft.Online.SharePoint.Powershell -DisableNameChecking

#Config Variables for Site URL, List Name
$SiteURL= "https://crescent.sharepoint.com/sites/sales/"
$ListName="Sales Contacts"

#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

#powershell sharepoint online get list
$List = $Ctx.Web.Lists.GetByTitle($ListName)
$Ctx.Load($List)
$Ctx.ExecuteQuery()

Write-host "Total Number of Items in the List:"$List.ItemCount
}
Catch [Exception] {
Write-host $_.Exception.Message -f Red
}
This script gets the given list and number of items from the list.

Related Post: SharePoint Online PowerShell to Get All Lists

SharePoint Online: How to Change Site Logo using PowerShell?

$
0
0
Changing logo is a common requirement when it comes to branding SharePoint online sites.

How to change Logo in SharePoint Online:
Changing logo in sharepoint online is a matter of few clicks. To add logo to sharepoint online, follow these steps
  • Login as a site Administrator to your SharePoint Online site. Click on Settings gear >> Select Site Settings >> On Site settings page, Click on "Title, description, and logo" link.
    SharePoint Online PowerShell Change Logo
  • That takes you to a page where you can set Logo for the site. you can use either a logo from your computer, or any existing logo from your SharePoint site (Even any existing image from the Internet too).
  • Click on "From Computer" link >> Browse and upload your logo file. Once you upload, the logo file gets saved into "Site Assets" Library of the site.SharePoint Online How to Change Site Logo using PowerShell
  • As soon as you upload a image for logo, You'll find the new logo reflected immediately in the top left hand side of the site. Optionally, you can enter description for the logo. This description becomes tool tip for your new logo. Click on "OK" button to save your changes. Click cancel to discard.
SharePoint Online PowerShell to Change Logo:
Lets use PowerShell script to change site logo in SharePoint online.
#Add PowerShell Module for SharePoint Online
Import-Module Microsoft.Online.SharePoint.Powershell -DisableNameChecking

##Configuration variables
$SiteUrl = "https://crescent.sharepoint.com/"
$LogoURL="/SiteAssets/Logo.png" #Existing file

Try {
#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
$Web = $Ctx.Web

#Change Logo
$Web.SiteLogoUrl = $LogoURL
$Web.Update()
$Ctx.ExecuteQuery()

Write-host "Logo Updated Successfully!" -ForegroundColor Green
}
Catch {
write-host -f Red "Error updating Logo!" $_.Exception.Message
}
Please note, the file URL at LogoURL must be an existing file in SharePoint online site. So, upload the logo to root of your site collection first.

PowerShell to Change the site logo for a site collection and its sub sites:
Lets change logo for all sites within a SharePoint online site collection.
#Add PowerShell Module for SharePoint Online
Import-Module Microsoft.Online.SharePoint.Powershell -DisableNameChecking

##Configuration variables
$SiteUrl = "https://crescent.sharepoint.com/Sites/Sales"
$LogoURL="/SiteAssets/Logo.png"

Try {
#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 Root web
$Web = $Ctx.Web
$Ctx.Load($Web)
$Ctx.ExecuteQuery()

#Function to change Logo for the given web
Function Update-Logo($Web)
{
#Update Logo
$Web.SiteLogoUrl = $LogoURL
$Web.Update()
$Ctx.ExecuteQuery()
Write-host "Updated Logo for Web:" $Web.URL

#Process each subsite in the site
$Subsites = $Web.Webs
$Ctx.Load($Subsites)
$Ctx.ExecuteQuery()
Foreach ($SubSite in $Subsites)
{
#Call the function Recursively
Update-Logo($Subsite)
}
}

#Call the function to change logo of the web
Update-Logo($Web)
}
Catch {
write-host -f Red "Error updating Logo!" $_.Exception.Message
}

Copy Group Memberships of a User in SharePoint using PowerShell

$
0
0
Requirement: Copy SharePoint Group Memberships of one user to another user

Solution: You can copy group memberships of one user to another user to have identical SharePoint Permissions for a SharePoint Site. Here is the PowerShell Script:

PowerShell Script to copy Group Memberships from One user to another:
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Configuration Parameters
$SiteURL="http://intranet.crescent.com"

$SourceUserID="i:0#.w|Crescent\Salaudeen"
$TargetUserID="Crescent\Opera"

#Get the web
$web = Get-SPWeb $SiteURL

#Get All group membershipss of the source user
$UserGroups = Get-SPUser $SourceUserID -web $SiteURL | Select -ExpandProperty Groups

#Get the Target User
$TargetUser = $web.EnsureUser($TargetUserID)

#Add target user to each group
Foreach($GroupName in $UserGroups)
{
Write-Host "Adding User to the Group:"$GroupName

#Get the Group
$Group = $Web.SiteGroups[$GroupName]
#Add User to Group
$Group.AddUser($TargetUser)
}
Alternatively, to add a user to SharePoint group, you can use Set-SPUser cmdlet
Set-SPUser -Identity $TargetUser -Web $SiteURL -Group $GroupName
However, if the group doesn't has access to the site, you'll get an error message: "The specified group does not exist."

If you want to clone a particular user's permissions, use this PowerShell script:  PowerShell to Copy Permissions in SharePoint

SharePoint Online: PowerShell to Send Email

$
0
0
We can send emails from SharePoint online, either with SPUtility's SendEmail function or with PowerShell cmdlet Send-MailMessage. Here are examples in both the cases:

PowerShell to Send Email in SharePoint Online:
Here is how to send an E-mail from SharePoint Online using PowerShell Client Side Object Model (CSOM) script.
Import-Module Microsoft.Online.SharePoint.Powershell -DisableNameChecking

#Config Parameters
$AdminSiteURL = "https://crescent-admin.sharepoint.com/"
$EmailFrom ="SPAdmin@crescent.com"
$EmailTo = "Salaudeen.Rajack@crescent.com"
$Subject ="SharePoint Online Storage Report"

#Setup Credentials and connect
$Cred = Get-Credential
Connect-SPOService -Url $AdminSiteURL -Credential $Cred

#Get Storage Usage of All Site collections
$SiteStorage = Get-SPOSite -Detailed | Select Url, StorageUsageCurrent

#Setup the site context for SPUtility SendEmail
$Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$Ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.UserName,$Cred.Password)

#Setup Email
$EmailProperties = New-Object Microsoft.SharePoint.Client.Utilities.EmailProperties
$EmailProperties.From = $EmailTo
$EmailProperties.To = [String[]] $EmailTo
$EmailProperties.Subject = $Subject
$EmailProperties.Body = $SiteStorage | Convertto-html
[Microsoft.SharePoint.Client.Utilities.Utility]::SendEmail($Ctx,$EmailProperties)
$Ctx.ExecuteQuery()
This sends Email using SPUtility's SendMail method with storage consumption of all site collections in SharePoint Online. Here from and To emails are Email addresses within the organization.
SharePoint Online PowerShell to Send Email

SharePoint Online PowerShell to Send Email:
This time, lets use PowerShell's native cmdlet Send-Mail message to send an Email from SharePoint online site.
Import-Module Microsoft.Online.SharePoint.Powershell -DisableNameChecking

#Config Parameters
$AdminSiteURL = "https://crescent-admin.sharepoint.com/"
$EmailFrom ="SPAdmin@crescent.com"
$EmailTo ="salaudeen.razhak@abraaj.com"
$EmailSubject ="Site Collection Storage Utilization Report"
$SMTP ="smtp.office365.com"

#Setup Credentials and connect
$Cred = Get-Credential
Connect-SPOService -Url $AdminSiteURL -Credential $Cred

#Get Storage Usage of All Site collections
$SiteStorage = Get-SPOSite -Detailed | Select Url, StorageUsageCurrent | Convertto-html | Out-String

#Send Email
Send-MailMessage -from $EmailFrom -To $EmailTo -Subject $EmailSubject -Body $SiteStorage -BodyAsHtml -smtpserver $SMTP -usessl -Credential $Cred -Port 587

SharePoint Online: How to Add Term Store Administrator

$
0
0
Problem:  SharePoint Online Term Store is read-Only to everyone including SharePoint Online Administrators!

Solution: Add Term Store Administrator! To work with Term store management tool in SharePoint online, you must have one of these roles: Term Store Administrator, Group Manager, or Contributor.

SharePoint Online Add Term Store Administrator
Here is how to add term store administrator in SharePoint Online:
  • Login to your SharePoint Online Admin center (E.g. https://YourDomain-Admin.SharePoint.com) 
  • Click on "Term Store" link in the left navigation to open the Term Store Management Tool.
  • In Term store management page, Select the taxonomy in the tree view. Now, from the General tab, Enter the people names in "Term Store Administrators" box. You can also use Browse button to find and add users. Once done, click Save button to commit your changes.
sharepoint online add term store administrator

 Group Manager vs Contributor:
You can also use Group Manager and Contributor groups to grant permissions at Term group level. They both can create or change a term set in the specified term group and in addition, Group Managers can add Contributors to that term group.
sharepoint online term store permissionsWe also have "Owners" at term set level to track Stakeholders for that term set. However, This doesn't give any permission to the term set, but only used to relate the contact information for that term set.

SharePoint Online: Delete Term Group in Term Store using PowerShell

$
0
0
How to Delete a Group in SharePoint Online Term Store:
  • Login to your SharePoint admin center site. (E.g. https://yourdomain-admin.sharepoint.com)
    Click the "term store" link on the left navigation menu.
  • From the taxonomy tree view, Select the term group which you want to delete. Click on the little arrow in the Term group Header >> Click on Delete Term Set option
    powershell to delete term group in sharepoint online
  • If the term group has any terms in it, you'll get an error message."The group has one or more term sets and can not be deleted. Move or delete all term sets from the group before deleting the Group". As the error message says, you got to delete all terms sets of the group in order to delete the group.
    delete term group in sharepoint online term store

PowerShell to Delete a Term Group 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"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Taxonomy.dll"

#Variables for Processing
$AdminURL = "https://crescent-admin.sharepoint.com/"
$TermGroupName ="Regions"

Try {
#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($AdminURL)
$Ctx.Credentials = $Credentials

#Get the term store
$TaxonomySession=[Microsoft.SharePoint.Client.Taxonomy.TaxonomySession]::GetTaxonomySession($Ctx)
$TermStore =$TaxonomySession.GetDefaultSiteCollectionTermStore()
$Ctx.Load($TaxonomySession)
$Ctx.Load($TermStore)
$Ctx.ExecuteQuery()

#Check if the given group exists
$TermGroups = $TermStore.Groups
$Ctx.Load($TermGroups)
$Ctx.ExecuteQuery()
$TermGroup = $TermGroups | Where-Object {$_.Name -eq $TermGroupName}

If($TermGroup -ne $NULL)
{
#Delete all Term sets in the Term group
$TermSets = $TermGroup.TermSets
$Ctx.Load($TermSets)
$Ctx.ExecuteQuery()

$TermSets | Foreach-object {
$_.DeleteObject()
$Ctx.ExecuteQuery()
}
$TermStore.CommitAll()

#Delete the Term Group
$TermGroup.DeleteObject()
$Ctx.ExecuteQuery()

Write-host "Term Group '$TermGroupName' Deleted Successfully!" -ForegroundColor Green
}
else
{
Write-host "Term Group '$TermGroupName' Doesn't Exists!" -ForegroundColor Yellow
}
}
Catch {
write-host -f Red "Error Deleting Term Group!" $_.Exception.Message
}

SharePoint Online: Delete Term Set using PowerShell

$
0
0
How to delete a Term Set in SharePoint Online?
To delete a term set from SharePoint online term store, follow these steps:
  • Login to your SharePoint Online admin center site. (E.g. https://yourdomain-admin.sharepoint.com)
  • Click the "Term store" link on the left navigation menu.
  • From the taxonomy tree view, Expand and select the term set you want to delete. Click on the little arrow in the Term set  >> Select "Delete Term Set" option. 
    SharePoint Online Delete Term Set using PowerShell
  • Confirm the prompt once to delete the term set from SharePoint Online term store.

PowerShell to Delete Term Set 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"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Taxonomy.dll"

#Variables for Processing
$AdminURL = "https://crescent-admin.sharepoint.com/"
$TermGroupName ="Regions"
$TermsetName="MENA"

Try {
#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($AdminURL)
$Ctx.Credentials = $Credentials

#Get the term store
$TaxonomySession=[Microsoft.SharePoint.Client.Taxonomy.TaxonomySession]::GetTaxonomySession($Ctx)
$TermStore =$TaxonomySession.GetDefaultSiteCollectionTermStore()
$Ctx.Load($TaxonomySession)
$Ctx.Load($TermStore)
$Ctx.ExecuteQuery()

#Get the term group
$TermGroup=$TermStore.Groups.GetByName($TermGroupName)

#Get the term set to delete
$TermSet = $TermGroup.TermSets.GetByName($TermsetName)

#Delete the term set
$TermSet.DeleteObject()
$Ctx.ExecuteQuery()

Write-host "Term Set '$TermSetName' Deleted Successfully!" -ForegroundColor Green
}
Catch {
write-host -f Red "Error Deleting Term Set!" $_.Exception.Message
}

Delete All Term Sets from a Term Group in SharePoint Online:
How about deleting all term sets from a term group?
#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.Taxonomy.dll"

#Variables for Processing
$AdminURL = "https://crescent-admin.sharepoint.com/"
$TermGroupName ="Regions"

Try {
#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($AdminURL)
$Ctx.Credentials = $Credentials

#Get the term store
$TaxonomySession=[Microsoft.SharePoint.Client.Taxonomy.TaxonomySession]::GetTaxonomySession($Ctx)
$TermStore =$TaxonomySession.GetDefaultSiteCollectionTermStore()
$Ctx.Load($TaxonomySession)
$Ctx.Load($TermStore)
$Ctx.ExecuteQuery()

#Get the term group
$TermGroups = $TermStore.Groups
$Ctx.Load($TermGroups)
$Ctx.ExecuteQuery()
$TermGroup = $TermGroups | Where-Object {$_.Name -eq $TermGroupName}

If($TermGroup -ne $NULL)
{
#Delete all Term sets in the Term group
$TermSets = $TermGroup.TermSets
$Ctx.Load($TermSets)
$Ctx.ExecuteQuery()

#Delete all Term Sets from the Group
$TermSets | Foreach-object {
$_.DeleteObject()
$Ctx.ExecuteQuery()
}

Write-host "All Term Sets Deleted Successfully from the Term Group '$TermGroupName'!" -ForegroundColor Green
}
else
{
Write-host "Term Group '$TermGroupName' Doesn't Exists!" -ForegroundColor Yellow
}
}
Catch {
write-host -f Red "Error Deleting Term Sets!" $_.Exception.Message
}

SharePoint Online: Export Term Set to CSV using PowerShell

$
0
0
Requirement: Had to extract all terms in a term set to CSV format in SharePoint Online.

Unfortunately, there is no way to export sharepoint online export term set from UI. But PowerShell can help!
sharepoint online powershell export term set


SharePoint Online PowerShell to Export Term Set
PowerShell to export all terms from a given term set in Term store of 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"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Taxonomy.dll"

#Variables for Processing
$AdminURL = "https://crescent-admin.sharepoint.com/"
$TermGroupName = "Regions"
$TermSetName = "East Africa"
$CSVFile="C:\Temp\TermSetData.csv"

Try {
#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($AdminURL)
$Ctx.Credentials = $Credentials

#Get the term store
$TaxonomySession=[Microsoft.SharePoint.Client.Taxonomy.TaxonomySession]::GetTaxonomySession($Ctx)
$TermStore =$TaxonomySession.GetDefaultSiteCollectionTermStore()
$Ctx.Load($TaxonomySession)
$Ctx.Load($TermStore)
$Ctx.ExecuteQuery()

#Get the Term Group
$TermGroup=$TermStore.Groups.GetByName($TermGroupName)

#Get the term set
$TermSet = $TermGroup.TermSets.GetByName($TermSetName)

#Get all tersm from the term set
$Terms = $TermSet.Terms
$Ctx.Load($Terms)
$Ctx.ExecuteQuery()

Write-Output $TermsetName > $CSVFile
#Export Terms to CSV
Foreach($Term in $Terms)
{
Write-Output $Term.Name >> $CSVFile
}
Write-host "Term Set Data Exported Successfully!" -ForegroundColor Green
}
Catch {
write-host -f Red "Error Exporting Term Set!" $_.Exception.Message
}
This script extract each term in the given term set into a CSV file. But wait! each term can go up to 7 levels deep! While the above script exports terms at one-single level, Here is my another PowerShell script to export terms and child terms of all levels of a given term set.
SharePoint Online Export Term Set
Export Term Set 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.Taxonomy.dll"

#Variables for Processing
$AdminURL = "https://crescent-admin.sharepoint.com/"
$TermGroupName = "Sectors"
$TermSetName = "Political Geography"
$CSVFile="C:\Temp\TermSet.csv"

#Custom Function get child terms of a given term
Function Get-Terms([Microsoft.SharePoint.Client.Taxonomy.Term] $Term,[String]$ParentTerm,[int] $Level)
{
$ChildTerms = $Term.Terms
$Ctx.Load($ChildTerms)
$Ctx.ExecuteQuery()
if($ParentTerm)
{
$ParentTerm = $ParentTerm + "," + $Term.Name
}
else
{
$ParentTerm = $Term.Name
}

Foreach ($SubTerm in $ChildTerms)
{
$Level = $Level + 1
#Terms may have upto 7 levels
$NumofCommas = 7 - $Level
$commas =""

#Append Commas
For ($j=0; $j -lt $NumofCommas; $j++)
{
$Commas = $Commas + ","
}

#Append the Output to CSV File
"," + "," + "," + $Term.IsAvailableForTagging + ",""$($Term.Description)""," + $ParentTerm + "," + $SubTerm.Name + $Commas >> $CSVFile

#Call the function recursively
Get-Terms -Term $SubTerm -ParentTerm $ParentTerm -Level $Level
}
}
Try {
#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($AdminURL)
$Ctx.Credentials = $Credentials

#Get the term store
$TaxonomySession=[Microsoft.SharePoint.Client.Taxonomy.TaxonomySession]::GetTaxonomySession($Ctx)
$TermStore =$TaxonomySession.GetDefaultSiteCollectionTermStore()
$Ctx.Load($TaxonomySession)
$Ctx.Load($TermStore)
$Ctx.ExecuteQuery()

#Write Termset CSV Header (As in the standard format)
"Term Set Name,Term Set Description,LCID,Available for Tagging,Term Description,Level 1 Term,Level 2 Term,Level 3 Term,Level 4 Term,Level 5 Term,Level 6 Term,Level 7 Term" > $CSVFile

#Get the Term Group
$TermGroup=$TermStore.Groups.GetByName($TermGroupName)

#Get the term set
$TermSet = $TermGroup.TermSets.GetByName($TermSetName)
$Ctx.Load($Termset)
$Ctx.ExecuteQuery()

#Get all tersm from the term set
$Terms = $TermSet.Terms
$Ctx.Load($Terms)
$Ctx.ExecuteQuery()

#Write 2nd line as Termset properties(As per standard format)
$TermSet.Name + ",""$($TermSet.Description)""," + $TermStore.DefaultLanguage + "," + $TermSet.IsAvailableForTagging + ",""$($Terms[0].Description)""," + $Terms[0].Name + "," + "," + "," + "," + "," + "," >> $CSVFile

#Process each Term in the termset
Foreach($Term in $Terms)
{
write-host $Term.Name
Get-Terms $Term -Level 1 -ParentTerm ""
}
Write-host "Term Set Data Exported Successfully!" -ForegroundColor Green
}
Catch {
write-host -f Red "Error Exporting Term Set!" $_.Exception.Message
}

SharePoint Online: Export Term Store Data to CSV using PowerShell

$
0
0
Requirement: Export Term store data from SharePoint Online site to a CSV file

Solution: There is no out of box way to export complete term store data in SharePoint online. However, we can utilize PowerShell to export term store data including all term groups, term sets and terms to a CSV file. Here is the script.
sharepoint online export term set

PowerShell to Export Term Store data to CSV:
#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.Taxonomy.dll"

#Variables for Processing
$AdminURL = "https://crescent-admin.sharepoint.com/"
$ReportOutput="C:\Temp\TermStoreData.csv"

Try {
#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($AdminURL)
$Ctx.Credentials = $Credentials

#Array to Hold Result - PSObjects
$ResultCollection = @()

#Get the term store
$TaxonomySession=[Microsoft.SharePoint.Client.Taxonomy.TaxonomySession]::GetTaxonomySession($Ctx)
$TermStore =$TaxonomySession.GetDefaultSiteCollectionTermStore()
$Ctx.Load($TaxonomySession)
$Ctx.Load($TermStore)
$Ctx.ExecuteQuery()

#Get all term groups
$TermGroups = $TermStore.Groups
$Ctx.Load($TermGroups)
$Ctx.ExecuteQuery()

#Iterate through each term group
Foreach($Group in $TermGroups)
{
#Get all Term sets in the Term group
$TermSets = $Group.TermSets
$Ctx.Load($TermSets)
$Ctx.ExecuteQuery()

#Iterate through each termset
Foreach($TermSet in $TermSets)
{
#Get all Terms from the term set
$Terms = $TermSet.Terms
$Ctx.Load($Terms)
$Ctx.ExecuteQuery()

#Iterate through each term
Foreach($Term in $Terms)
{
$TermData = new-object PSObject
$TermData | Add-member -membertype NoteProperty -name "Group" -Value $Group.Name
$TermData | Add-member -membertype NoteProperty -name "TermSet" -Value $Termset.Name
$TermData | Add-member -membertype NoteProperty -name "Term" -Value $Term.Name
$ResultCollection += $TermData
}
}
}
#Export Results to a CSV File
$ResultCollection | Export-csv $ReportOutput -notypeinformation

Write-host "Term Store Data Successfully Exported!" -ForegroundColor Green
}
Catch {
write-host -f Red "Error Exporting Termstore Data!" $_.Exception.Message
}
This produces a CSV file as in this image:
sharepoint online powershell export term set

To import this CSV data to any other term store, use my another article: PowerShell to Import Term Store Data from CSV in SharePoint Online

SharePoint Online: Delete Column from List using PowerShell

$
0
0
Requirement: SharePoint Online delete column from list.

How to remove a column from SharePoint Online List?
To delete a list column, follow these steps:

  • Go to List settings by going to List tab >> Under Settings group, click on List Settings button in the ribbon.
  • Under the List Settings page, in the Columns section, click on the column title you wish to delete.
  • Scroll down and Click on Delete button.
    sharepoint online list delete column
  • Confirm the deletion prompt by clicking OK.
This deletes sharepoint online list column.

PowerShell to delete column from list 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"

#Variables for Processing
$SiteURL="https://crescent.sharepoint.com"
$ListName= "Projects"
$ColumnName="Project Code"

Try {
#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)

#Get the Column to delete
$Column = $List.Fields.GetByTitle($ColumnName)
$Column.DeleteObject()
$Ctx.ExecuteQuery()

Write-host "Column '$ColumnName' deleted Successfully!" -ForegroundColor Green
}
Catch {
write-host -f Red "Error Deleting Column from List!" $_.Exception.Message
}

SharePoint Online: Rename Folder using PowerShell

$
0
0
PowerShell to Rename Folder 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"

#Variables
$SiteURL="https://crescent.sharepoint.com"
$FolderURL="/Project Documents/Active" #Relative URL
$FolderNewURL="/Project Documents/InActive"

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 Folder
$Folder = $Ctx.Web.GetFolderByServerRelativeUrl($FolderURL)
$Ctx.Load($Folder)
$Ctx.ExecuteQuery()

#Rename Folder
$Folder.MoveTo($FolderNewURL)
$Ctx.ExecuteQuery()

Write-host -f Green "Folder has been renamed to new URL:"$FolderNewURL
}
Catch {
write-host -f Red "Error Renaming Folder!" $_.Exception.Message
}

Get All Available Cmdlets in SharePoint Online Management Shell

$
0
0
Here is a nifty trick to find all available cmdlets in SharePoint online management shell.
  • Open SharePoint Online Management Shell and Enter:
    Get-Command | ? { $_.ModuleName -eq "Microsoft.Online.SharePoint.PowerShell" }
sharepoint online powershell cmdlet
This lists down all cmdlets from SharePoint Online Management Shell.

SharePoint Online: Add Site Column to List using PowerShell

$
0
0
Requirement: Add an existing site column to SharePoint list or library using PowerShell.

How to Add a Site Column to SharePoint Online List?
Site columns in SharePoint provides great reusability without having to recreate same columns multiple times! Once created, we can utilize them in any number of lists and libraries. To add a site column to SharePoint list, follow these steps:

  • Go to List Settings >> Under Columns, Click on "Add from existing site columns" link.
  • From the available site columns, pick the required site column(s) and click on Add button.
    sharepoint online powershell to add site column to list
  • Click OK to save your changes.

Add Site Column to List or 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"

#Variables
$SiteURL="https://crescent.sharepoint.com"
$ListName="Projects"
$SiteColumnName="Department"

$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
$Web = $Ctx.web

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

#Get the Site column
$Field = $Web.Fields.GetByTitle($SiteColumnName)

#Add the site column to the list
$List.Fields.Add($Field)
$ctx.ExecuteQuery()

Write-host "Site Column Added to the List Successfully!" -f Green
Lets add some error handling to the above code to handle scenarios, such as:
  • What if the given site column doesn't exist?
  • What if the given site column is already added to the list?
  • What if the given list doesn't exist? or what if the given credentials are invalid?, etc.
PowerShell to Add a Site Column to SharePoint 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"

#Parameters
$SiteURL="https://crescent.sharepoint.com"
$ListName="Projects"
$SiteColumnName="Department"

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
$Web = $Ctx.web

#Get the Site column from web
$SiteColumns = $Web.Fields
$Ctx.Load($SiteColumns)
$Ctx.ExecuteQuery()
$SiteColumn = $SiteColumns | Where {$_.Title -eq $SiteColumnName}

#Check if given site column exists
if($SiteColumn -eq $Null)
{
Write-host "Site Column $SiteColumnName doesn't exists!" -f Yellow
}
else
{
#Get the list
$List=$Ctx.Web.Lists.GetByTitle($ListName)

#Check if the Filed exist in list already
$Fields = $List.Fields
$Ctx.Load($List)
$Ctx.Load($Fields)
$Ctx.ExecuteQuery()
$Field = $Fields | where {$_.Title -eq $SiteColumnName}
if($Field -ne $NULL)
{
Write-host "Column Name $SiteColumnName already exists in the list!" -f Yellow
}
else
{
#Add the site column to the list
$NewColumn = $List.Fields.Add($SiteColumn)
$ctx.ExecuteQuery()

Write-host "Site Column Added to the List Successfully!" -f Green
}
}
}
Catch {
write-host -f Red "Error Adding Site Column to List!" $_.Exception.Message
}

SharePoint Online: Create Site Column using PowerShell

$
0
0
Site columns in SharePoint Online
Site columns provides great re-usability in SharePoint without having to recreate fields every time  you need them in lists and libraries. They save a lot of time especially when you have to standardize columns, create columns with data (such as choice fields) or assign default values to them. Once created at the top site, a site column can be utilized in any list or library or even content types throughout your site collection (or across site collections with content type hub).

How to Create Site Column in SharePoint Online?
To create site column in SharePoint online, follow these steps:
  • Login to SharePoint online site. Click on Site Settings Gear and select Site Settings.
  • On Site Settings page, Click on "Site Columns" link under "Web Designer Galleries" group. 
  • In Site Columns page, Click on "Create" Link at the top.
    sharepoint online powershell create site column
  • In create column page, Enter the name for your site column. Select the column type, Specify settings specific to the column. Click on "OK" button at the bottom to complete creating site column in SharePoint Online.
    create site columns using powershell in sharepoint online
    Now the site column will be added to the site.
Create Site Columns using PowerShell in SharePoint Online:
Here is my collection of PowerShell scripts to create site columns in SharePoint online using client side object mode (CSOM).
Important: Field Schema XML is case sensitive!

Create Single Line of Text Site Column 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"

#Parameters
$SiteURL="https://crescent.sharepoint.com"
$ColumnName="ProjectCode"
$IsRequired = "TRUE"
$ColumnGroup="Crescent Projects"

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 Site columns from the site
$Fields = $Ctx.web.Fields
$Ctx.Load($Fields)
$Ctx.executeQuery()

#Check if the column name exists
$NewField = $Fields | where {$_.Title -eq $ColumnName}
if($NewField -ne $NULL)
{
Write-host "Site Column $ColumnName already exists!" -f Yellow
}
else
{
#Define XML for Field Schema
$FieldSchema = "<Field Type='Text' DisplayName='$ColumnName' Name='$ColumnName' required='$IsRequired' Group='$ColumnGroup'/>"
$NewField = $Fields.AddFieldAsXml($FieldSchema,$True,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
$Ctx.ExecuteQuery()

Write-host "Site Column Created Successfully!" -ForegroundColor Green
}
}
Catch {
write-host -f Red "Error Creating Site Column!" $_.Exception.Message
}

Add Multiple Lines of Text Field using PowerShell: 
This time, lets wrap the code into a re-usable function
#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 add Multiline Text Field
Function Add-MultilineSiteColumn()
{
param
(
[Parameter(Mandatory=$true)] [string] $SiteURL,
[Parameter(Mandatory=$true)] [string] $ColumnName,
[Parameter(Mandatory=$true)] [string] $NumberofLines,
[Parameter(Mandatory=$true)] [string] $IsRequired,
[Parameter(Mandatory=$true)] [string] $RichText,
[Parameter(Mandatory=$true)] [string] $ColumnGroup
)

#Generate new GUID for Field ID
$FieldID = ([GUID]::NewGuid()).GUID

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 Site columns from the site
$Fields = $Ctx.web.Fields
$Ctx.Load($Fields)
$Ctx.executeQuery()

#Check if the column name exists
$NewField = $Fields | where {$_.Title -eq $ColumnName}
if($NewField -ne $NULL)
{
Write-host "Site Column $ColumnName already exists!" -f Yellow
}
else
{
#Define XML for Field Schema
$FieldSchema = "<Field Type='Note' ID='{$FieldID}' DisplayName='$ColumnName' Name='$ColumnName' RichText='$RichText' Required='$IsRequired' Group='$ColumnGroup'/>"
$NewField = $Fields.AddFieldAsXml($FieldSchema,$True,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
$Ctx.ExecuteQuery()

Write-host "Site Column Created Successfully!" -ForegroundColor Green
}
}
Catch {
write-host -f Red "Error Creating Site Column!" $_.Exception.Message
}
}

#Define value for parameters
$SiteURL="https://crescent.sharepoint.com"
$ColumnName="ProjectDescription"
$IsRequired = "TRUE"
$ColumnGroup="Crescent Projects"
$RichText ="FALSE"
$NumberofLines="5"

#Call the function to create Multiline site column
Add-MultilineSiteColumn -SiteURL $SiteURL -ColumnName $ColumnName -IsRequired $IsRequired -NumberofLines $NumberofLines -RichText $RichText -ColumnGroup $ColumnGroup


PowerShell  to Create Person or Group (People Picker) Site Column to 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 add site column
Function Add-PersonOrGroupSiteColumn()
{
param
(
[Parameter(Mandatory=$true)] [string] $SiteURL,
[Parameter(Mandatory=$true)] [string] $ColumnName,
[Parameter(Mandatory=$true)] [string] $ColumnDisplayName,
[Parameter(Mandatory=$true)] [string] $IsRequired,
[Parameter(Mandatory=$true)] [string] $ColumnGroup
)

#Generate new GUID for Field ID
$FieldID = ([GUID]::NewGuid()).GUID

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 Site columns from the site
$Fields = $Ctx.web.Fields
$Ctx.Load($Fields)
$Ctx.executeQuery()

#Check if the column name exists already
$NewField = $Fields | where { ($_.Internalname -eq $ColumnName) -or ($_.Title -eq $ColumnDisplayName) }
if($NewField -ne $NULL)
{
Write-host "Site Column $ColumnName already exists!" -f Yellow
}
else
{
#Frame Choices
$ChoiceOptions=""
$Choices = $ChoiceValues.Split(",")
foreach ($Choice in $Choices)
{
$ChoiceOptions = $ChoiceOptions + "<CHOICE>$Choice</CHOICE>"
}
#Define XML for Field Schema
$FieldSchema = "<Field Type='User' ID='{$FieldID}' DisplayName='$ColumnDisplayName' Name='$ColumnName' Required='$IsRequired' Group='$ColumnGroup' ShowField='ImnName' List='UserInfo' UserSelectionMode='PeopleOnly' />"
$FieldSchema
$NewField = $Fields.AddFieldAsXml($FieldSchema,$True,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
$Ctx.ExecuteQuery()

Write-host "Site Column Created Successfully!" -ForegroundColor Green
}
}
Catch {
write-host -f Red "Error Creating Site Column!" $_.Exception.Message
}
}

#Set parameter values
$SiteURL="https://crescent.sharepoint.com"
$ColumnName="ProjectMembers"
$ColumnDisplayName="Project Members"
$IsRequired = "TRUE"
$ColumnGroup="Crescent Projects"

#Call the function to create site column
Add-PersonOrGroupSiteColumn -SiteURL $SiteURL -ColumnName $ColumnName -ColumnDisplayName $ColumnDisplayName -IsRequired $IsRequired -ColumnGroup $ColumnGroup

Add Date and Time Site Column to 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 add site column
Function Add-DateTimeSiteColumn()
{
param
(
[Parameter(Mandatory=$true)] [string] $SiteURL,
[Parameter(Mandatory=$true)] [string] $ColumnName,
[Parameter(Mandatory=$true)] [string] $ColumnDisplayName,
[Parameter(Mandatory=$true)] [string] $Format,
[Parameter(Mandatory=$true)] [string] $IsRequired,
[Parameter(Mandatory=$true)] [string] $ColumnGroup
)

#Generate new GUID for Field ID
$FieldID = ([GUID]::NewGuid()).GUID

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 Site columns from the site
$Fields = $Ctx.web.Fields
$Ctx.Load($Fields)
$Ctx.executeQuery()

#Check if the column name exists already
$NewField = $Fields | where { ($_.Internalname -eq $ColumnName) -or ($_.Title -eq $ColumnDisplayName) }
if($NewField -ne $NULL)
{
Write-host "Site Column $ColumnName already exists!" -f Yellow
}
else
{
#Define XML for Field Schema
$FieldSchema = "<Field Type='DateTime' ID='{$FieldID}' DisplayName='$ColumnDisplayName' Name='$ColumnName' Format='$Format' Required='$IsRequired' Group='$ColumnGroup'/>"
$NewField = $Fields.AddFieldAsXml($FieldSchema,$True,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
$Ctx.ExecuteQuery()

Write-host "Site Column Created Successfully!" -ForegroundColor Green
}
}
Catch {
write-host -f Red "Error Creating Site Column!" $_.Exception.Message
}
}

#Set parameter values
$SiteURL="https://crescent.sharepoint.com"
$ColumnName="ProjectStartDate"
$ColumnDisplayName="Project Start Date"
$Format="DateOnly"
$IsRequired = "FALSE"
$ColumnGroup="Crescent Projects"

#Call the function to create site column
Add-DateTimeSiteColumn -SiteURL $SiteURL -ColumnName $ColumnName -ColumnDisplayName $ColumnDisplayName -IsRequired $IsRequired -Format $Format -ColumnGroup $ColumnGroup

PowerShell CSOM script to Add Currency Site Column for 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 add site column
Function Add-CurrencySiteColumn()
{
param
(
[Parameter(Mandatory=$true)] [string] $SiteURL,
[Parameter(Mandatory=$true)] [string] $ColumnName,
[Parameter(Mandatory=$true)] [string] $ColumnDisplayName,
[Parameter(Mandatory=$true)] [string] $LCID,
[Parameter(Mandatory=$true)] [string] $IsRequired,
[Parameter(Mandatory=$true)] [string] $ColumnGroup
)

#Generate new GUID for Field ID
$FieldID = ([GUID]::NewGuid()).GUID

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 Site columns from the site
$Fields = $Ctx.web.Fields
$Ctx.Load($Fields)
$Ctx.executeQuery()

#Check if the column name exists already
$NewField = $Fields | where { ($_.Internalname -eq $ColumnName) -or ($_.Title -eq $ColumnDisplayName) }
if($NewField -ne $NULL)
{
Write-host "Site Column $ColumnName already exists!" -f Yellow
}
else
{
#Define XML for Field Schema
$FieldSchema = "<Field Type='Currency' ID='{$FieldID}' DisplayName='$ColumnDisplayName' Name='$ColumnName' LCID='$LCID' Required='$IsRequired' Group='$ColumnGroup'/>"
$NewField = $Fields.AddFieldAsXml($FieldSchema,$True,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
$Ctx.ExecuteQuery()

Write-host "Site Column Created Successfully!" -ForegroundColor Green
}
}
Catch {
write-host -f Red "Error Creating Site Column!" $_.Exception.Message
}
}

#Set parameter values
$SiteURL="https://crescent.sharepoint.com"
$ColumnName="TotalInvestment"
$ColumnDisplayName="Total Investment Amount"
$LCID="1081" #India
$IsRequired = "TRUE"
$ColumnGroup="Crescent Projects"

#Call the function to create site column
Add-CurrencySiteColumn -SiteURL $SiteURL -ColumnName $ColumnName -ColumnDisplayName $ColumnDisplayName -IsRequired $IsRequired -LCID $LCID -ColumnGroup $ColumnGroup

Refer https://msdn.microsoft.com/en-us/library/microsoft.sharepoint.splocale.lcid.aspx for all LCIDs.

SharePoint Online: Add Number Site Column 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"

#Custom function to add site column
Function Add-NumberSiteColumn()
{
param
(
[Parameter(Mandatory=$true)] [string] $SiteURL,
[Parameter(Mandatory=$true)] [string] $ColumnName,
[Parameter(Mandatory=$true)] [string] $ColumnDisplayName,
[Parameter(Mandatory=$true)] [string] $IsRequired,
[Parameter(Mandatory=$true)] [string] $ColumnGroup
)

#Generate new GUID for Field ID
$FieldID = ([GUID]::NewGuid()).GUID

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 Site columns from the site
$Fields = $Ctx.web.Fields
$Ctx.Load($Fields)
$Ctx.executeQuery()

#Check if the column name exists
$NewField = $Fields | where { ($_.Internalname -eq $ColumnName) -or ($_.Title -eq $ColumnDisplayName) }
if($NewField -ne $NULL)
{
Write-host "Site Column $ColumnName already exists!" -f Yellow
}
else
{
#Define XML for Field Schema
$FieldSchema = "<Field Type='Number' ID='{$FieldID}' DisplayName='$ColumnDisplayName' Name='$ColumnName' Required='$IsRequired' Group='$ColumnGroup'/>"
$NewField = $Fields.AddFieldAsXml($FieldSchema,$True,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
$Ctx.ExecuteQuery()

Write-host "Site Column Created Successfully!" -ForegroundColor Green
}
}
Catch {
write-host -f Red "Error Creating Site Column!" $_.Exception.Message
}
}

#Set parameter values
$SiteURL="https://crescent.sharepoint.com"
$ColumnName="HeadCount"
$ColumnDisplayName="Head Count"
$IsRequired = "TRUE"
$ColumnGroup="Crescent Projects"

#Call the function to create site column
Add-NumberSiteColumn -SiteURL $SiteURL -ColumnName $ColumnName -ColumnDisplayName $ColumnDisplayName -IsRequired $IsRequired -ColumnGroup $ColumnGroup

How to Add Choice Site Column to 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"

#Custom function to add site column
Function Add-ChoiceSiteColumn()
{
param
(
[Parameter(Mandatory=$true)] [string] $SiteURL,
[Parameter(Mandatory=$true)] [string] $ColumnName,
[Parameter(Mandatory=$true)] [string] $ColumnDisplayName,
[Parameter(Mandatory=$true)] [string] $ChoiceValues,
[Parameter(Mandatory=$true)] [string] $IsRequired,
[Parameter(Mandatory=$true)] [string] $ColumnGroup
)

#Generate new GUID for Field ID
$FieldID = ([GUID]::NewGuid()).GUID

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 Site columns from the site
$Fields = $Ctx.web.Fields
$Ctx.Load($Fields)
$Ctx.executeQuery()

#Check if the column name exists already
$NewField = $Fields | where { ($_.Internalname -eq $ColumnName) -or ($_.Title -eq $ColumnDisplayName) }
if($NewField -ne $NULL)
{
Write-host "Site Column $ColumnName already exists!" -f Yellow
}
else
{
#Frame Choices
$ChoiceOptions=""
$Choices = $ChoiceValues.Split(",")
foreach ($Choice in $Choices)
{
$ChoiceOptions = $ChoiceOptions + "<CHOICE>$Choice</CHOICE>"
}
#Define XML for Field Schema
$FieldSchema = "<Field Type='Choice' ID='{$FieldID}' DisplayName='$ColumnDisplayName' Name='$ColumnName' Required='$IsRequired' Group='$ColumnGroup'> <CHOICES>$ChoiceOptions</CHOICES></Field>"
$FieldSchema
$NewField = $Fields.AddFieldAsXml($FieldSchema,$True,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
$Ctx.ExecuteQuery()

Write-host "Site Column Created Successfully!" -ForegroundColor Green
}
}
Catch {
write-host -f Red "Error Creating Site Column!" $_.Exception.Message
}
}

#Set parameter values
$SiteURL="https://crescent.sharepoint.com"
$ColumnName="ProjectDepartment"
$ColumnDisplayName="Project Department"
$IsRequired = "TRUE"
$ChoiceValues="IT,Sales,Operations,Marketing,HR"
$ColumnGroup="Crescent Projects"

#Call the function to create site column
Add-ChoiceSiteColumn -SiteURL $SiteURL -ColumnName $ColumnName -ColumnDisplayName $ColumnDisplayName -IsRequired $IsRequired -ChoiceValues $ChoiceValues -ColumnGroup $ColumnGroup
You can also add Type="MultiChoice", Format="RadioButtons" to customize it further.

Create Lookup Site Column 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"

#Custom function to add site column
Function Add-LookupSiteColumn()
{
param
(
[Parameter(Mandatory=$true)] [string] $SiteURL,
[Parameter(Mandatory=$true)] [string] $ColumnName,
[Parameter(Mandatory=$true)] [string] $ColumnDisplayName,
[Parameter(Mandatory=$true)] [string] $LookupListName,
[Parameter(Mandatory=$true)] [string] $LookupField,
[Parameter(Mandatory=$true)] [string] $IsRequired,
[Parameter(Mandatory=$true)] [string] $ColumnGroup
)

#Generate new GUID for Field ID
$FieldID = ([GUID]::NewGuid()).GUID

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 Site columns from the site
$Web = $Ctx.web
$Ctx.Load($Web)
$Fields = $web.Fields
$Ctx.Load($Fields)
$Ctx.executeQuery()

#Check if the column name exists already
$NewField = $Fields | where { ($_.Internalname -eq $ColumnName) -or ($_.Title -eq $ColumnDisplayName) }
if($NewField -ne $NULL)
{
Write-host "Site Column $ColumnName already exists!" -f Yellow
}
else
{
#Get IDs of Lookup List and Web
$LookupList=$Web.Lists.GetByTitle($LookupListName)
$Ctx.Load($LookupList)
$Ctx.executeQuery()

$LookupListID= $LookupList.id
$LookupWebID=$Ctx.web.Id

#Define XML for Field Schema
$FieldSchema = "<Field Type='Lookup' ID='{$FieldID}' DisplayName='$ColumnDisplayName' Name='$ColumnName' Required='$IsRequired' Group='$ColumnGroup' List='$LookupListID' WebId='$LookupWebID' ShowField='$LookupField' />"
$NewField = $Fields.AddFieldAsXml($FieldSchema,$True,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
$Ctx.ExecuteQuery()

Write-host "Site Column Created Successfully!" -ForegroundColor Green
}
}
Catch {
write-host -f Red "Error Creating Site Column!" $_.Exception.Message
}
}

#Set parameter values
$SiteURL="https://crescent.sharepoint.com"
$ColumnName="ParentProject"
$ColumnDisplayName="Parent Project"
$IsRequired = "TRUE"
$ColumnGroup="Crescent Projects"
$LookupList="Projects" #Parent Lookup
$LookupField="ProjectName"

#Call the function to create site column
Add-LookupSiteColumn -SiteURL $SiteURL -ColumnName $ColumnName -ColumnDisplayName $ColumnDisplayName -IsRequired $IsRequired -ColumnGroup $ColumnGroup -LookupList $LookupList -LookupField $LookupField
Refer this MSDN article to frame schema XML attributes for site columns: https://msdn.microsoft.com/en-us/library/office/aa979575.aspx

SharePoint Online: Create Date and Time Column in List using PowerShell

$
0
0
How to Add Date and Time Column to SharePoint Online List?
  • Browse to your SharePoint Online site and then Navigate to the target list in which you want to create date and time column.
  • Under the List tab, click on "Create Column" button in the ribbon.
  • Provide the Name to your new column, specify the type as "Date and Time" 
  • Fill other optional values and Click on "OK" to create date and time column in SharePoint Online list.
    SharePoint Online Create Date and Time Column in List using PowerShell
Here is the PowerShell script to create date and time column for SharePoint online list or library.

PowerShell to Add Date and Time Field in SharePoint Online 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"

#Custom function to add column to list
Function Add-DateTimeColumnToList()
{
param
(
[Parameter(Mandatory=$true)] [string] $SiteURL,
[Parameter(Mandatory=$true)] [string] $ListName,
[Parameter(Mandatory=$true)] [string] $Name,
[Parameter(Mandatory=$true)] [string] $DisplayName,
[Parameter(Mandatory=$true)] [string] $Description,
[Parameter(Mandatory=$true)] [string] $Format,
[Parameter(Mandatory=$true)] [string] $IsRequired,
[Parameter(Mandatory=$true)] [string] $FriendlyDisplayFormat,
[Parameter(Mandatory=$true)] [string] $EnforceUniqueValues
)

#Generate new GUID for Field ID
$FieldID = New-Guid

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.ExecuteQuery()

#Check if the column exists in list already
$Fields = $List.Fields
$Ctx.Load($Fields)
$Ctx.executeQuery()
$NewField = $Fields | where { ($_.Internalname -eq $Name) -or ($_.Title -eq $DisplayName) }
if($NewField -ne $NULL)
{
Write-host "Column $Name already exists in the List!" -f Yellow
}
else
{
#Define XML for Field Schema
$FieldSchema = "<Field Type='DateTime' ID='{$FieldID}' Name='$Name' StaticName='$Name' DisplayName='$DisplayName' Format='$Format' Required='$IsRequired' Description='$Description' EnforceUniqueValues='$EnforceUniqueValues' FriendlyDisplayFormat='$FriendlyDisplayFormat' />"
$NewField = $List.Fields.AddFieldAsXml($FieldSchema,$True,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldInternalNameHint)
$Ctx.ExecuteQuery()

Write-host "New Column Added to the List Successfully!" -ForegroundColor Green
}
}
Catch {
write-host -f Red "Error Adding Column to List!" $_.Exception.Message
}
}

#Set parameter values
$SiteURL="https://crescent.sharepoint.com"
$ListName="Projects"
$Name="ProjectStartDate" #Column Name
$DisplayName="Project Start Date"
$Description="Enter the Project Start Date"
$Format="DateOnly" #DateTime
$IsRequired = "FALSE"
$EnforceUniqueValues="FALSE"
$FriendlyDisplayFormat="Disabled" #Relative

#Call the function to add column to list
Add-DateTimeColumnToList -SiteURL $SiteURL -ListName $ListName -Name $Name -DisplayName $DisplayName -IsRequired $IsRequired -Format $Format -EnforceUniqueValues $EnforceUniqueValues -FriendlyDisplayFormat $FriendlyDisplayFormat -Description $Description

SharePoint Online: Add Multiple Lines of Text Columnto List using PowerShell

$
0
0
How to Add Multiple Lines of Text Field to List in SharePoint Online?
  • Browse to your SharePoint Online site and Navigate to the target list in which you want to add Choice column.
  • Under the List tab, click on "Create Column" button in the ribbon.
  • Provide the Name to your new column, specify the type as "Multiple lines of text"
    PowerShell to add multiline text field to sharepoint online list
  • Fill other optional values such as Number of lines, Type of text, append changes to existing text, etc. and Click on "OK" to create Multiple lines of text column in SharePoint Online list.

PowerShell to Create Multiple Lines of Text Column in SharePoint Online 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"

#Custom function to add column to list
Function Add-MultilineTextColumnToList()
{
param
(
[Parameter(Mandatory=$true)] [string] $SiteURL,
[Parameter(Mandatory=$true)] [string] $ListName,
[Parameter(Mandatory=$true)] [string] $Name,
[Parameter(Mandatory=$true)] [string] $DisplayName,
[Parameter(Mandatory=$false)] [string] $Description="",
[Parameter(Mandatory=$false)] [string] $IsRequired = "FALSE",
[Parameter(Mandatory=$false)] [string] $IsRichText="FALSE",
[Parameter(Mandatory=$false)] [string] $NumLines = "6",
[Parameter(Mandatory=$false)] [string] $EnhancedRichText = "FALSE"
)

#Generate new GUID for Field ID
$FieldID = New-Guid

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.ExecuteQuery()

#Check if the column exists in list already
$Fields = $List.Fields
$Ctx.Load($Fields)
$Ctx.executeQuery()
$NewField = $Fields | where { ($_.Internalname -eq $Name) -or ($_.Title -eq $DisplayName) }
if($NewField -ne $NULL)
{
Write-host "Column $Name already exists in the List!" -f Yellow
}
else
{
#Define XML for Field Schema
if($EnhancedRichText -eq "TRUE") #Enhanced Rich Text Mode
{
$FieldSchema = "<Field Type='Note' ID='{$FieldID}' DisplayName='$DisplayName' Name='$Name' Description='$Description' Required='$IsRequired' NumLines='$NumLines' RichText='TRUE' RichTextMode='FullHtml' IsolateStyles='TRUE' />"
}
else #Plain Text or Rich Text
{
$FieldSchema = "<Field Type='Note' ID='{$FieldID}' DisplayName='$DisplayName' Name='$Name' Description='$Description' Required='$IsRequired' NumLines='$NumLines' RichText='$IsRichText' />"
}

$NewField = $List.Fields.AddFieldAsXml($FieldSchema,$True,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldInternalNameHint)
$Ctx.ExecuteQuery()

Write-host "New Column Added to the List Successfully!" -ForegroundColor Green
}
}
Catch {
write-host -f Red "Error Adding Column to List!" $_.Exception.Message
}
}

#Set parameter values
$SiteURL="https://crescent.sharepoint.com"
$ListName="Projects"
$Name="ProjectDescription"
$DisplayName="Project Description"
$Description="Enter the Project Description"
$IsRichText="FALSE" #FALSE for Plain text / TRUE for Rich text
$EnhancedRichText="FALSE" #FALSE for Rich text / TRUE for Enhanced Rich Text, Takes Precedence over IsRichText parameter value

#Call the function to add column to list
Add-MultilineTextColumnToList -SiteURL $SiteURL -ListName $ListName -Name $Name -DisplayName $DisplayName -Description $Description -IsRichText $IsRichText -EnhancedRichText $EnhancedRichText

SharePoint Online: Add Managed Metadata Column to List using PowerShell

$
0
0
SharePoint Online: How to Add Managed Metadata Field to List or Library:
  • Browse to your SharePoint Online site and Navigate to the target list in which you want to add Managed Metadata column.
  • Under the List tab, click on "Create Column" button in the ribbon.
  • Provide the Name to your new column, specify the field type as "Managed Metadata" 
    Add Managed Metadata field to SharePoint Online List using PowerShell
  • Scroll down and select the appropriate Term set or Term from the taxonomy store.
    PowerShell to create managed metadata column in SharePoint Online List
  • Fill other optional values and Click on "OK" to create Managed Metadata field in SharePoint Online list.

PowerShell to Create Managed Metadata column in SharePoint Online 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"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Taxonomy.dll"

#Custom function to add column to list
Function Add-ManagedMetadataColumnToList()
{
param
(
[Parameter(Mandatory=$true)] [string] $SiteURL,
[Parameter(Mandatory=$true)] [string] $ListName,
[Parameter(Mandatory=$true)] [string] $Name,
[Parameter(Mandatory=$true)] [string] $DisplayName,
[Parameter(Mandatory=$false)] [string] $Description="",
[Parameter(Mandatory=$false)] [string] $IsRequired = "FALSE",
[Parameter(Mandatory=$false)] [string] $EnforceUniqueValues = "FALSE",
[Parameter(Mandatory=$true)] [string] $TermGroupName,
[Parameter(Mandatory=$true)] [string] $TermSetName
)

#Generate new GUID for Field ID
$FieldID = New-Guid

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 web, List and Lookup list
$Web = $Ctx.web
$List = $Web.Lists.GetByTitle($ListName)
$LookupList = $Web.Lists.GetByTitle($LookupListName)
$Ctx.Load($Web)
$Ctx.Load($List)
$Ctx.Load($LookupList)
$Ctx.ExecuteQuery()

#Check if the column exists in list already
$Fields = $List.Fields
$Ctx.Load($Fields)
$Ctx.executeQuery()
$NewField = $Fields | where { ($_.Internalname -eq $Name) -or ($_.Title -eq $DisplayName) }
if($NewField -ne $NULL)
{
Write-host "Column $Name already exists in the List!" -f Yellow
}
else
{
#Get the Term set data
$TaxonomySession=[Microsoft.SharePoint.Client.Taxonomy.TaxonomySession]::GetTaxonomySession($Ctx)
$TermStore =$TaxonomySession.GetDefaultSiteCollectionTermStore()
$Ctx.Load($TaxonomySession)
$Ctx.Load($TermStore)
$Ctx.ExecuteQuery()
#Get the Term Group
$TermGroup=$TermStore.Groups.GetByName($TermGroupName)
#Get the term set
$TermSet = $TermGroup.TermSets.GetByName($TermSetName)
$Ctx.Load($TermSet)
$Ctx.ExecuteQuery()

#Create Managed Metadata Column
$FieldSchema = "<Field Type='TaxonomyFieldType' ID='{$FieldID}' DisplayName='$DisplayName' Name='$Name' Description='$Description' Required='$IsRequired' EnforceUniqueValues='$EnforceUniqueValues' />"
$NewField = $List.Fields.AddFieldAsXml($FieldSchema,$True,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldInternalNameHint)
$Ctx.ExecuteQuery()

#Bind Managed Metadata Termset to the column
$TaxField = [Microsoft.SharePoint.Client.ClientContext].GetMethod("CastTo").MakeGenericMethod([Microsoft.SharePoint.Client.Taxonomy.TaxonomyField]).Invoke($Ctx, $NewField)
$TaxField.SspId = $TermStore.Id
$TaxField.TermSetId = $TermSet.Id
$TaxField.Update()
$Ctx.ExecuteQuery()

Write-host "New Column Added to the List Successfully!" -ForegroundColor Green
}
}
Catch {
write-host -f Red "Error Adding Column to List!" $_.Exception.Message
}
}

#Set parameter values
$SiteURL="https://crescent.sharepoint.com"
$ListName="Projects"
$Name="ProjectRegions"
$DisplayName="Project Regions"
$Description="Select the Project Region"
$TermGroupName="Regions"
$TermSetName="MENA"

#Call the function to add column to list
Add-ManagedMetadataColumnToList -SiteURL $SiteURL -ListName $ListName -Name $Name -DisplayName $DisplayName -Description $Description -TermGroupName $TermGroupName -TermSetName $TermSetName

SharePoint Online: Add Calculated Column to List using PowerShell

$
0
0
Requirement: Add Calculated Column to SharePoint Online List

How to Add Calculated column to SharePoint Online List?
  • Browse to your SharePoint Online site and Navigate to the target list in which you want to create calculated column.
  • Under the List tab, click on "Create Column" button in the ribbon.
  • Provide the Name to your new column, specify the type as "Calculated (calculation based on other columns)"
    Add calculated Column to SharePoint Online List using PowerShell
  • Enter the Formula for your calculated column in "Formula" field and specify the return type of the data. 
  • Scroll down and set other parameters such as decimal places and format of the data and Click on "OK" to create Calculated field in SharePoint Online list.

PowerShell to Create Calculated Column to List 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"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Taxonomy.dll"

#Custom function to add column to list
Function Add-CalculatedColumnToList()
{
param
(
[Parameter(Mandatory=$true)] [string] $SiteURL,
[Parameter(Mandatory=$true)] [string] $ListName,
[Parameter(Mandatory=$true)] [string] $Name,
[Parameter(Mandatory=$true)] [string] $DisplayName,
[Parameter(Mandatory=$false)] [string] $Description="",
[Parameter(Mandatory=$true)] [string] $FieldsReferenced,
[Parameter(Mandatory=$true)] [string] $Formula,
[Parameter(Mandatory=$true)] [string] $ResultType
)

#Generate new GUID for Field ID
$FieldID = New-Guid

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.ExecuteQuery()

#Check if the column exists in list already
$Fields = $List.Fields
$Ctx.Load($Fields)
$Ctx.executeQuery()
$NewField = $Fields | where { ($_.Internalname -eq $Name) -or ($_.Title -eq $DisplayName) }
if($NewField -ne $NULL)
{
Write-host "Column $Name already exists in the List!" -f Yellow
}
else
{
#Frame FieldRef Field
$FieldRefXML=""
$FieldRefs = $FieldsReferenced.Split(",")
foreach ($Ref in $FieldRefs)
{
$FieldRefXML = $FieldRefXML + "<FieldRef Name='$Ref' />"
}

#Create Column in the list
$FieldSchema = "<Field Type='Calculated' ID='{$FieldID}' DisplayName='$DisplayName' Name='$Name' Description='$Description' ResultType='$ResultType' ReadOnly='TRUE'><Formula>$Formula</Formula><FieldRefs>$FieldRefXML</FieldRefs></Field>"
$FieldSchema
$NewField = $List.Fields.AddFieldAsXml($FieldSchema,$True,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldInternalNameHint)
$Ctx.ExecuteQuery()

Write-host "New Column Added to the List Successfully!" -ForegroundColor Green
}
}
Catch {
write-host -f Red "Error Adding Column to List!" $_.Exception.Message
}
}

#Set parameter values
$SiteURL="https://crescent.sharepoint.com"
$ListName="Projects"
$Name="TotalInvestmentBuffer"
$DisplayName="Total Investment Buffer"
$Description="5 Percentage in Total Investment"
$Formula = "=([Total Investment]*5)/100"
$ResultType="Currency"
$FieldsReferenced="[Total Investment]" #Fields Names participating in Formula. Should be Comma (,) Separated

#Call the function to add column to list
Add-CalculatedColumnToList -SiteURL $SiteURL -ListName $ListName -Name $Name -DisplayName $DisplayName -Description $Description -Formula $Formula -ResultType $ResultType -FieldsReferenced $FieldsReferenced

SharePoint Online: Find and Delete Orphaned Users using PowerShell

$
0
0
find and delete orphaned users in sharepoint online

What is "Orphaned Users" in SharePoint Online?
In short, Orphaned users are those who deleted from the authentication provider (such as removed from Active Directory when user leaves the organization), and still continue to exist in SharePoint online sites! scanning each user in SharePoint online site collection for orphaned users could take days to complete! Since, Here is my PowerShell script to search for orphan users and delete them.

Pr-Requisites: Before using this script, you need to have SharePoint Online Management Shell (https://www.microsoft.com/en-us/download/details.aspx?id=35588) and Azure Active Directory Module (https://technet.microsoft.com/en-us/library/dn975125.aspx) installed on your machine!

Find Orphan Users in SharePoint Online using PowerShell:
This script scans each and every user from the given site collection URLand exports list of orphaned users to a CSV file.

#Import SharePoint Online and Azure Online modules
Import-Module Microsoft.Online.SharePoint.Powershell
Import-Module MSOnline

Function Generate-OrphanedUsersReport ()
{
param
(
[Parameter(Mandatory=$true)] [string] $AdminURL,
[Parameter(Mandatory=$true)] [string] $SiteURL,
[Parameter(Mandatory=$true)] [string] $ReportOutput
)
Try {
#Get Credentials to connect
$Cred = Get-Credential

#Connect to SharePoint and Azure AD
Connect-MsolService -Credential $cred
Connect-SPOService -Url $AdminURL -Credential $Cred

#Function to check if a user account exists
Function Check-UserExists()
{
Param( [Parameter(Mandatory=$true)] [string]$UserID )

$User=Get-Msoluser -UserPrincipalName $UserID -Erroraction SilentlyContinue
if ($User -ne $null)
{
Return $True
}
else
{
Return $false
}
}
$OrphanedUsers = @()

#Get all users of a given SharePoint Online site collection
$AllUsers = Get-SPOUser $SiteURL -Limit ALL

Foreach($User in $AllUsers)
{
#Exclude Built-in User Accounts and Security Groups
if(($User.DisplayName.ToLower() -ne "nt authority\authenticated users") -and ($User.LoginName.ToLower() -ne "sharepoint\system") -and
($User.DisplayName.ToLower() -ne "sharepoint app") -and ($user.IsGroup -eq $false ) -and(-not $user.DisplayName.ToLower().Contains("_spocache")) -and
(-not $user.DisplayName.ToLower().Contains("_spocrawl")) -and ($User.DisplayName.ToLower() -ne "sharepoint service administrator") -and
($User.DisplayName.ToLower() -ne "guest contributor") -and ($User.DisplayName.ToLower() -ne "everyone except external users")-and ($User.DisplayName.ToLower() -ne "company administrator"))
{
Write-host "Checking user $($user.DisplayName)" -f Yellow
#Check if user exists
if((Check-UserExists $User.LoginName) -eq $False)
{
Write-Host "User Doesn't Exists: $($user.DisplayName) - $($User.LoginName)" -f Red

#Send the Result to CSV
$Result = new-object PSObject
$Result| add-member -membertype NoteProperty -name "LoginName" -Value $User.LoginName
$Result | add-member -membertype NoteProperty -name "DisplayName" -Value $User.DisplayName
$OrphanedUsers += $Result
}
}
}
#Export results to CSV
$OrphanedUsers | Export-csv $ReportOutput -notypeinformation

Write-host "Orphan Users Report Generated to $ReportOutput" -f Green
}

Catch {
write-host -f Red "Error Deleting Unique Permissions!" $_.Exception.Message
}
}

#Config Parameters
$AdminURL ="https://crescent-admin.sharepoint.com"
$SiteURL = "https://crescent.sharepoint.com"
$ReportOutput="C:\Temp\OrphanUsers.csv"

#Call the function to find and generate orphaned users report
Generate-OrphanedUsersReport -AdminURL $AdminURL -SiteURL $SiteURL -ReportOutput $ReportOutput
Be sure the CSV generated doesn't include any built-in user accounts and groups, prior providing the CSV file as an input to the next step of removing orphan users!

How to Delete Orphan Users from SharePoint Online with PowerShell: 
While its possible to remove each user from SharePoint online site collection individually, it becomes cumbersome when we have large number of orphan users to remove! Here is the PowerShell script to read orphan users from the CSV file generated in previous step and remove them all in one go!
#Import SharePoint Online module
Import-Module Microsoft.Online.SharePoint.Powershell

Function Remove-OrphanedUsers ()
{
param
(
[Parameter(Mandatory=$true)] [string] $AdminURL,
[Parameter(Mandatory=$true)] [string] $SiteURL,
[Parameter(Mandatory=$true)] [string] $ReportInput
)
Try {
#Get Credentials to connect
$Cred = Get-Credential

#Connect to SharePoint online
Connect-SPOService -Url $AdminURL -Credential $Cred

#Get the Data from CSV and Add to SharePoint List
$OrphanUsers = Import-Csv $ReportInput
Foreach ($Row in $OrphanUsers)
{
#Remove user from site
Remove-SPOUser -Site $SiteURL -LoginName $Row.LoginName
Write-host "Removed the Orphaned User $($Row.DisplayName) from $($SiteURL)"
}
Write-host "Orphaned Users Removed from SharePoint Online Site!"
}
Catch {
write-host -f Red "Error Deleting Unique Permissions!" $_.Exception.Message
}
}

#Config Parameters
$AdminURL ="https://crescent-admin.sharepoint.com"
$SiteURL = "https://crescent.sharepoint.com"
$ReportInput="C:\Temp\OrphanUsers.csv"

#Call the function to Remove Orphaned users
Remove-OrphanedUsers -AdminURL $AdminURL -SiteURL $SiteURL -ReportInput $ReportInput
You can use these functions to find and/or remove orphaned users from all site collections. Just add:
Get-SPOSite -Limit all | ForEach-Object { 
#Call the function to find and generate orphaned users report
Generate-OrphanedUsersReport -AdminURL $AdminURL -SiteURL $_.Url -ReportOutput $ReportOutput
}
Viewing all 1058 articles
Browse latest View live


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