Showing posts with label PowerShell. Show all posts
Showing posts with label PowerShell. Show all posts

September 11, 2025

SharePoint: Connect using access tokens in PnP PowerShell

Task

I had an string array of SPO site collection URLs and I needed to execute PowerShell script that fetches comments and likes of app pages across all of these site collections. For getting actual page specific likes and comments, there is PnP PowerShell commands Get-PnPPageLikedByInformation and Get-PnPListItemComment, and you get nice object array including date, and even comment content. No problem there.

However, in my one-time executable script I didn't want to do interactive login for each of those site collections, so I needed a way to somehow persist the credentials and reuse them every time I called Connect-PnPOnline towards each site collection.

Back in the days, all they way in on-prem SharePoint, you could use Get-Credential once and store the credentials in a variable and include that as the parameter in the connection PS command, whatever that was. It, however, hasn't worked in a long time when there are MFA and other requirements towards signing in to online services such as SharePoint Online.

Good thing there is a solution.

Solution

Access tokens to the rescue! 

# first connect normally to SPO, but remember to return the connection using ReturnConnection parameter
$conn = Connect-PnPOnline -ClientId [YOUR_CLIENT_ID] -Url [YOUR_SPO_URL] -ReturnConnection

# magic is here, first get the access token, you only need to do this once (note that token will expire at some point)
$token = Get-PnPAccessToken -Connection $conn -ResourceTypeName SharePoint

# then whenever you want to connect to new site collection, use the token instead of ClientId
$newConn = Connect-PnPOnline -AccessToken $token -Url [NEW_SPO_URL] -ReturnConnection

May 22, 2019

SharePoint: Determining if library root level folders have broken permission inheritance using PnP PowerShell

This simple script can be used to determine status of permission inheritance of document library root level folders.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
$siteUrl = "https://mytenant.sharepoint.com/sites/somesitecollection"
Connect-PnPOnline -Url $siteUrl -UseWebLogin
$context = Get-PnPContext 

$list = Get-PnPList "SomeLibrary"

$folders = $list.RootFolder.Folders
$context.Load($folders)
$context.ExecuteQuery()

foreach($folder in $folders)
{
  if($folder.ItemCount -gt 0)
  {    
    $f = Get-PnPFolder -Url $folder.ServerRelativeUrl -Includes ListItemAllFields.RoleAssignments, ListItemAllFields.HasUniqueRoleAssignments

    $context.Load($f)
    $context.ExecuteQuery()

    Write-Host $f.ServerRelativeUrl -> $f.ListItemAllFields.HasUniqueRoleAssignments
  }
}

January 25, 2018

Disable friendly formatting on date columns on SharePoint site collection

Problem

After migrating content to SharePoint 2016, all date columns were in Friendly display format. I needed a neat way to update them across the site collection using PowerShell, but all scripts that attempted to modify the FriendlyDisplayFormat property of a column had some issues.

This one on Social Technet didn’t work as our site wasn’t in English, nor did this or this. Some looked alright, but threw error “The property 'FriendlyDisplayFormat' cannot be found on this object. Verify that the property exists and can be set.”

Solution

$WebCollection = Get-SPSite "<SITEURL>" -Limit All | Get-SPWeb -Limit All
 
foreach($web in $WebCollection)
{
     Write-Host "Connected to "$web.Title -ForegroundColor Yellow

    $lists = $web.Lists
 
     foreach($list in @($lists))
     {
         Write-Host "Connected to ...$list" -ForegroundColor Yellow
        
         foreach($field in @($list.Fields))
         {      
             $column = $list.Fields.GetFieldByInternalName($field.InternalName)
       
             if($column.Type -eq "DateTime")
             {                  
                 Write-Host "Connected to ......"$column.Title -ForegroundColor Yellow
                 $column.FriendlyDisplayFormat = 1
                 $column.update()               
             }
         }
     }

    $web.Dispose()
}

December 11, 2017

SharePoint Online: Hide content type on list

Task

Hide Content type on SharePoint Online document library.

Solution

Requires PnP-Powershell, installation instructions here.

Connect-PnPOnline –Url “https://tenant.sharepoint.com”
$ctx = Get-PnPContext

$web = Get-PnPWeb

$doclib = Get-PnPList -Identity "<DOCLIBNAME>" -Includes ContentTypes,RootFolder.UniqueContentTypeOrder

$rootFolder = $doclib.RootFolder

$ct = $doclib.ContentTypes | where {$_.Name -eq "<CT TO BE HIDDEN>"}
$ct2 = $doclib.ContentTypes | where {$_.Name -eq "<CT TO BE HIDDEN, USUALLY FOLDER>"}

if($rootFolder.UniqueContentTypeOrder -eq $null)
{
     $contentTypesInPlace = New-Object -TypeName 'System.Collections.Generic.List[Microsoft.SharePoint.Client.ContentTypeId]'

    #$contentTypesInPlace = $doclib.ContentTypes | where {$_.Id -ne $ct.Id}
     foreach($ct in $doclib.ContentTypes | where {$_.Id -ne $ct.Id -and $_.Id -ne $ct2.Id})
     {
         $contentTypesInPlace.Add($ct.Id)
     }
}
else
{           
     $contentTypesInPlace = [System.Collections.ArrayList] $rootFolder.UniqueContentTypeOrder
     $contentTypesInPlace = $contentTypesInPlace | where {$_.StringValue -ne $ct.Id}
}
         
#Set the UniqueContentTypeOrder to the collection we made above
$rootFolder.UniqueContentTypeOrder = [System.Collections.Generic.List[Microsoft.SharePoint.Client.ContentTypeId]] $contentTypesInPlace
         
#Update the root folder
$rootFolder.Update()               
Execute-PnPQuery

March 9, 2017

SharePoint: Batch delete access requests

Problem

On on-premises SharePoint 2013 there was a web site where there were hundreds of pending access requests that needed to be removed. Approving or Declining requests was not desired, they just needed to be removed without any email being sent to the users.
There is no deletion option in browser UI, and after adding traditional AllItems.aspx view using SharePoint Designer, deleting requests one by one would’ve taken very long time, as while the All Items view allowed me to select multiple rows, there was no Delete button in any toolbar nor ribbon.

Solution

Simple PowerShell script did the trick.

NOTE! This also removes the history, so only run it if you do not wish to persist the access request history for the site.

$web = Get-SPWeb https://teamsites.company.com/teams/teamsiteA
$items = $web.Lists["Access Requests"].Items
while($items.Count -gt 0)
{
    Write-Host "Deleting: $($items[0].Title)"
    $items[0].Delete()
}

February 15, 2017

SharePoint: Batch update CSWP query using PowerShell

Task

Needed to update CSWP query on a lots of sites programmatically. URL of the content was changed so needed to change the Path rule in CSWP.

Solution

Script below recursively uses Office PnP PowerShell, so first install it using

Install-Module SharePointPnPPowerShellOnline -AllowClobber

Script goes through all subsites, publishing pages on the subsites, and web parts on the publishing pages and updates the path search rule, but obviously you can just modify the first two parameters to make any change you wish.

NOTE! It determines if web part is CSWP by looking at the DataProviderJSON property of the web part.

Flip $saveChanges to $true to actually persist changes.

$stringToFind = @('path:\"https://xyz.sharepoint.com/oldsite/')
$stringToReplace = @('path:\"https://xyz.sharepoint.com/newsite/')
$saveChanges = $false
$credentials = Get-Credential

function UpdateSearchWebParts($webUrl)
{
    Connect-PnPOnline -Url $webUrl -Credentials $credentials

    Write-Host "Updating CSWP source string:"$stringToFind " with Target string " $stringToReplace
   
    foreach($subweb in Get-PnPSubWebs -Recurse)
    {
        Write-Host "Subweb '$($subweb.Title)'"
       
        # Get pages
        foreach($page in Get-PnPListItem -Web $subweb -List "pages" -Fields "FileRef" | Where { $_.FieldValues.FSObjType -eq 0})
        {  
            Write-Host "Page '$($page["FileRef"])'"
         
            if($saveChanges) {
                Set-PnPFileCheckedOut -Url $page["FileRef"] -Web $subweb
            }
           
            #Get CSWP
            $webparts = Get-PnPWebPart -Web $subweb -ServerRelativePageUrl $page["FileRef"]
            foreach($webpart in $webparts)
            {
                if($webpart.WebPart.Properties.FieldValues.DataProviderJSON -eq $null -or !$webpart.WebPart.Properties.FieldValues.DataProviderJSON.Contains($stringToFind))
                {
                    continue
                }

                Write-Host "Web part: " $webpart.WebPart.Title               
               
                Write-Host "Old: '"$webpart.WebPart.Properties.FieldValues.DataProviderJSON"'"
                $newJson = $webpart.WebPart.Properties.FieldValues.DataProviderJSON.Replace($stringToFind, $stringToReplace)
                Write-Host "New: '"$newJson"'"

                if($saveChanges) {
                    Set-PnPWebPartProperty -ServerRelativePageUrl $page["FileRef"] -Identity $webpart.Id -Key DataProviderJSON -Value $newJson
                }
            }

            if($saveChanges) {
                Set-PnPFileCheckedIn -Url $page["FileRef"] -Web $subweb -CheckinType MajorCheckIn
            }           
        }       
    }
}

UpdateSearchWebParts https://xyz.sharepoint.com

March 4, 2016

PowerShell 4.0 GetEnumerator not working if array variable name length > 20 chars

Problem

Was going about my daily PowerShell (4.0) life and run into issue where the following script didn’t output any rows.

$moduleSiteCollections = @{
    'Field Intelligence' = 'fi';
    'News Feeds' = 'nf';
    'Key Developments' = 'kd'
}
foreach ($sitecoll in $moduleSiteCollections.GetEnumerator()) {   
    Write-Host $($sitecoll.Value)
}

Solution

If the length of the name of the variable holding the array is longer than 20 characters, GetEnumerator won’t return any results, so reduce variable name to 20 characters or less. Or use PowerShell 5.0.

The following script works fine.

$moduleSiteCollection = @{
    'Field Intelligence' = 'fi';
    'News Feeds' = 'nf';
    'Key Developments' = 'kd'
}
foreach ($sitecoll in $moduleSiteCollection.GetEnumerator()) {   
    Write-Host $($sitecoll.Value)
}

November 30, 2015

SharePoint Multi-Tenancy: Search returns no hits from tenant site

Problem

After setting up on-premises SharePoint 2013 in multi-tenancy mode, and configuring all Service Applications, everything else was working fine, but there was no search results being returned from the tenant site collections.

I could see from SharePoint search logs that the site contents were crawled properly, but even a broad search query such as Size>0 didn’t return any hits.

Thoughts

I had to tweak AutoSPInstaller scripts to enable creating different Service Applications using the -Partitioned or -PartitionMode parameter, and I had missed to set -Partitioned parameter for the Search Service Application Proxy.

I got to the bottom of this by looking at the Properties of the Proxy using PowerShell like this:

PS C:\AutoSPInstaller> Get-SPEnterpriseSearchServiceApplicationProxy

DisplayName          TypeName             Id
-----------          --------             --                                 
Search Service Ap... Search Service Ap... c54d9470-714a-46ff-983c-33422d466a4c

PS C:\AutoSPInstaller> $sp = Get-SPEnterpriseSearchServiceApplicationProxy c54d9470-714a-46ff-983c-33422d466a4c

PS C:\AutoSPInstaller> $sp.Properties

DisplayName                    Value                       
----                           -----
Microsoft.Office.Server.Uti... UnPartitioned

Note the “Unpartitioned”, it should say “UniquePartitionPerSubscription”.

Solution

  1. Remove Search Service Application Proxy
  2. Create it using the -Partitioned parameter

June 9, 2015

SharePoint: Create Publishing page with specific Modified date using PowerShell

Problem

I had to import thousands of lines from CSV file and turn those into SharePoint publishing pages. Overall, it was easy with PowerShell, but whenever I used $item.File.Publish("") at the end of creating new Publishing Page to publish it, the Modified date was set to current date and time. I tried all possible variations and tricks I could come up with until I came up with the solution.

Solution

You need to turn off minor versioning for the Pages list and only call CheckIn for the individual items. Doing CheckIn doesn't touch the Modified date. After you've imported all items, you can enable minor versioning on the list, and all items will remain published.

$ver = $host | select version
if ($ver.Version.Major -gt 1)  {$Host.Runspace.ThreadOptions = "ReuseThread"}
Add-PsSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
Import-Module WebAdministration -ErrorAction SilentlyContinue

$web = Get-SPWeb https://sharepoint.mydomain.com/m/nf/0
$list = $web.Lists["Pages"]

#Important to disable this first to get rid of
$list.EnableMinorVersions = $false
$list.EnableVersioning = $false
$list.Update()

# Change it to real layout name
$PageLayout =  $pweb.GetAvailablePageLayouts() | Where-Object {$_.ServerRelativeUrl -eq "/m/nf/_catalogs/masterpage/myportal/article.aspx"}

# Imports modified Rawdata from CSV file to MiPages - change filename if needed
Import-Csv -Delimiter ";" -Path (Resolve-Path RawData.csv) | ForEach-Object {
   
    # Page title
    $PageTitle = $_.Title
   
    # Place to save news, filename format is i+ID.aspx
    $PageUrl = "i" + [string]$_.ID + ".aspx"
   
    $SourceDate = Get-Date $_.Date

    Write-Host "Creating $($PageUrl)"

    # Create blank page
    $page = $pWeb.AddPublishingPage($PageUrl,$PageLayout)
       
    # Sets listitem fields
    $item = $page.ListItem
    $item["Title"] = $PageTitle
    $item["Created"] = $SourceDate
    $item["Modified"] = $SourceDate

    # Update list items
    $item.UpdateOverwriteVersion()

    # Check-in and publish page  
    $page.CheckIn("")      
}

$list.EnableMinorVersions = $true
$list.EnableVersioning = $true
$list.Update()

September 24, 2014

SharePoint: Replacing owners of Term Sets and Terms using PowerShell and CSOM

SCRIPT

Param (
    [Parameter(Mandatory=$True)]
    [string]$Url,
    [Parameter(Mandatory=$True)]
     [string]$OldOwner,
    [Parameter(Mandatory=$True)]
    [string]$NewOwner,
    [Parameter(Mandatory=$True)]
    [string]$AdminUsername
)

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client")
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.Runtime")
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.Taxonomy")

## Stop here
$lcid = "1033"

Write-Host "Please enter password for $($Url):"
$pwd = Read-Host -AsSecureString

# connect/authenticate to SharePoint Online and get ClientContext object..
$sCtx = New-Object Microsoft.SharePoint.Client.ClientContext($Url)
$sCredentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($AdminUsername, $pwd)
$sCtx.Credentials = $sCredentials

if (!$sCtx.ServerObjectIsNull.Value)
{
    Write-Host "Connected to SharePoint Online: " $sCtx.Url "" -ForegroundColor Green

    $sTaxonomySession = [Microsoft.SharePoint.Client.Taxonomy.TaxonomySession]::GetTaxonomySession($sCtx)
    $sTaxonomySession.UpdateCache()
    $sCtx.Load($sTaxonomySession)
    $sCtx.ExecuteQuery()

    if (!$sTaxonomySession.ServerObjectIsNull)
    {
        Write-Host "Taxonomy session: " $sTaxonomySession.Path.Identity "" -ForegroundColor Green

        $sTermStore = $sTaxonomySession.GetDefaultSiteCollectionTermStore()
        $sCtx.Load($sTermStore)
        $sCtx.ExecuteQuery()

        if ($sTermStore.IsOnline)
        {
            Write-Host "Term Store connected:" $sTermStore.Id "" -ForegroundColor Green
            $sCtx.Load($sTermStore.Groups)
            $sCtx.ExecuteQuery()

            foreach ($sTermGroup in $sTermStore.Groups)
            {
                Write-Host "Term Group: " $sTermGroup.Name "-" $sTermGroup.Id "" -ForegroundColor Green
                $termSets = $sTermGroup.TermSets
                $sCtx.Load($termSets)
                $sCtx.ExecuteQuery()

                foreach($termSet in $termSets)
                {
                    Write-Host "Term Set found: " $termSet.Name ", Current Owner: " $termSet.Owner "" -ForegroundColor Green

                    If($termSet.Owner -match $OldOwner)
                    {
                        Write-Host "Replacing old termset owner!" -ForegroundColor Yellow
                        $termSet.Owner = $NewOwner
                    }

                    $terms = $termSet.Terms
                    $sCtx.Load($terms)
                    $sCtx.ExecuteQuery()
                    foreach($term in $terms)
                    {
                        Write-Host "Term found: " $term.Name ", Current Owner: " $term.Owner "" -ForegroundColor Green

                        If($term.Owner -match $OldOwner)
                        {
                            Write-Host "Replacing old term owner!" -ForegroundColor Yellow
                            $term.Owner = $NewOwner
                        }
                    }
                }               
            }

            #####
            Write-Host "Rolling back..." -ForegroundColor Cyan
            $sTermStore.RollbackAll()
            #Write-Host "Committing..." -ForegroundColor Cyan
            #$sTermStore.CommitAll()
            #####

            $sTermStore.UpdateCache()

            Write-Host "Done!" -ForegroundColor Green
        }
    }
}

 

USAGE

You need to uncommend the CommitAll command at the end, and comment the RollbackAll command in order for the script to store changes in database. Script will loop through all term groups and sets and terms and change owner of term sets and terms.

.\ReplaceTermSetOwner.ps1 -Url https://myspsite.sharepoint.com –OldOwner oldowner@myspsite.com -NewOwner newowner@myspsite.com -AdminUsername adminusername@myspsite.com

SharePoint: Change Term Set Owner using PowerShell via CSOM

SCRIPT

Param (
    [Parameter(Mandatory=$True)]
    [string]$Url,
    [Parameter(Mandatory=$True)]
    [string]$NewOwner,
    [Parameter(Mandatory=$True)]
    [string]$TermGroupName,
    [Parameter(Mandatory=$True)]
    [string]$TermSetName,
    [Parameter(Mandatory=$True)]
    [string]$AdminUsername
)
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client")
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.Runtime")
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.Taxonomy")
$lcid = "1033"
Write-Host "Please enter password for $($Url):"
$pwd = Read-Host -AsSecureString
# connect/authenticate to SharePoint Online and get ClientContext object..
$sCtx = New-Object Microsoft.SharePoint.Client.ClientContext($Url)
$sCredentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($AdminUsername, $pwd)
$sCtx.Credentials = $sCredentials
if (!$sCtx.ServerObjectIsNull.Value)
{
    Write-Host "Connected to SharePoint Online: " $sCtx.Url "" -ForegroundColor Green
    $sTaxonomySession = [Microsoft.SharePoint.Client.Taxonomy.TaxonomySession]::GetTaxonomySession($sCtx)
    $sTaxonomySession.UpdateCache()
    $sCtx.Load($sTaxonomySession)
    $sCtx.ExecuteQuery()
    if (!$sTaxonomySession.ServerObjectIsNull)
    {
        Write-Host "Taxonomy session: " $sTaxonomySession.Path.Identity "" -ForegroundColor Green
        $sTermStore = $sTaxonomySession.GetDefaultSiteCollectionTermStore()
        $sCtx.Load($sTermStore)
        $sCtx.ExecuteQuery()
        if ($sTermStore.IsOnline)
        {
            Write-Host "Term Store connected:" $sTermStore.Id "" -ForegroundColor Green
            $sCtx.Load($sTermStore.Groups)
            $sCtx.ExecuteQuery()
            foreach ($sTermGroup in $sTermStore.Groups)
            {
                if ($sTermGroup.Name -eq $TermGroupName)
                {
                    Write-Host "Term Group: " $sTermGroup.Name "-" $sTermGroup.Id "" -ForegroundColor Green
                    $termSets = $sTermGroup.TermSets
                    $sCtx.Load($termSets)
                    $sCtx.ExecuteQuery()
                    $termSet = $termSets.GetByName($TermSetName)
                    $sCtx.Load($termSet)
                    $sCtx.ExecuteQuery()
                        Write-Host "Term Set found: " $termSet.Name ", Current Owner: " $termSet.Owner "" -ForegroundColor Green
                        $termSet.Owner = $NewOwner
                         Write-Host "Owner changed to: " $NewOwner "" -ForegroundColor Cyan
                }
            }
            Write-Host "Committing..." -ForegroundColor Cyan
            $sTermStore.CommitAll()
            $sCtx.ExecuteQuery()
            Write-Host "Done!" -ForegroundColor Green
        }
    }
}

USAGE

.\ChangeTermSetOwner.ps1 -Url https://myspsite.sharepoint.com -NewOwner newowner@myspsite.com -TermGroupName MyTermGroup -TermSetName MyTermSet -AdminUsername adminusername@myspsite.com

June 23, 2011

SharePoint: Organization browser not showing Manager when Manager is set using PowerShell

Problem:
You are using PowerShell to set value for user’s Manager and you use email address when setting the value of the UserProfile[“Manager”].Value.

Looking at user profile, the Manager property looks correct, it even resolves domain account properly.

userprofile

However, Organization browser is not showing Managers for users.

Solution:
Don’t use e-mail when setting Manager value:

$userProfile["Manager"].Value = $managerEmail

instead use manager’s account name:

$managerProfile = $profileMgr.GetUserProfile($managerEmail)   
$userProfile["Manager"].Value = $managerProfile["AccountName"]

PS. CSV file we use for importing profiles doesn’t contain AD account name, that’s why I’m using email in the first place.