Sharepoint PnP List: How to "Group by" columns using Powershell - powershell

I want to group a Sharepoint list by a column using powershell, so when users access this list, it's already grouped.
I know the List settings already has this Here, but I want to be able to control this via a powershell script that resets the list to data read from a local server.
Below images provide additional clarity of my question.
Columns not grouped together
Columns grouped together

Please take a reference of below powershell script:
#Set Variables
$SiteURL = "https://abc.sharepoint.com/sites/s01"
$ListName = "your list name"
$Username='admin#abc.onmicrosoft.com'
$Password = 'xxxx'
#region Credentials
[SecureString]$SecurePass = ConvertTo-SecureString $Password -AsPlainText -Force
[System.Management.Automation.PSCredential]$PSCredentials = New-Object System.Management.Automation.PSCredential($Username, $SecurePass)
#endregion Credentials
#Connect to PNP Online
Connect-PnPOnline -Url $SiteURL -Credentials $PSCredentials
#Get the Client Context
$Context = Get-PnPContext
#Get the List View
$View = Get-PnPView -Identity "All Items" -List $ListName
$Context.Load($View)
$Context.ExecuteQuery()
$View.ViewQuery
$ViewQuery = '<GroupBy Collapse="TRUE" GroupLimit="30"><FieldRef Name="num" /></GroupBy>' + $View.ViewQuery
#Update the view Query
$View.ViewQuery = $ViewQuery
$View.Update()
$Context.ExecuteQuery()
More references:
https://www.sharepointdiary.com/2018/04/sharepoint-online-powershell-to-update-list-view.html
https://learn.microsoft.com/en-us/powershell/module/sharepoint-pnp/get-pnpview?view=sharepoint-ps
BR

Related

what is the PNP Power shell command equivalent to "New-Object Microsoft.SharePoint.SPFieldUserValue"

Inside SharePoint 2013 i use this command to get the username of the Created By field:-
$Approver = New-Object Microsoft.SharePoint.SPFieldUserValue($sourceweb,$ApprovalListItem["Created By"])
But in SharePoint online what is the equivalent command in PnP Power-Shell script?
Thanks
Per my test, you can try following script to retrieve username of Created By field
#Parameters
$SiteURL = "https://xxx.sharepoint.com/sites/xxx"
$ListName = "TestList"
#Connect to Source Site
Connect-PnPOnline -Url $SiteURL
$ListItems = Get-PnPListItem -List $ListName -PageSize 500 | Where {$_["FileLeafRef"] -like "*.*"}
foreach($ListItem in $ListItems){
Write-Host "Title:" $ListItem["Title"]
Write-Host "Author:" $ListItem["Author"].LookupValue
}

Powershell: Set-PnPListItem remove taxonomy value (empty value)[SharePoint Online]

I build a script to map some old taxonomy value from old columns to new columns and tax. values. There are some cases where I have to remove or empty current meta data. Does someone know how it works with Set-PnPListItem. While updating I pass the list item and a hash #{field=value}. Updating works fine but can't remove or empty.
To remove or empty I tried to set the value to -1, $null and "" but nothing works and I will get this error: Set-PnPListItem : Value cannot be null.
Error message
Here is my test result.
#region Variables
$Username = "admin#xxx.onmicrosoft.com"
$Password = "Password"
$siteURL = "https://xxx.sharepoint.com/sites/lee"
#endregion Variables
#region Credentials
[SecureString]$SecurePass = ConvertTo-SecureString $Password -AsPlainText -Force
[System.Management.Automation.PSCredential]$PSCredentials = New-Object System.Management.Automation.PSCredential($Username, $SecurePass)
#endregion Credentials
Connect-PnPOnline -Url $siteURL -Credentials $PSCredentials
Set-PnPListItem -List "ListMetaData" -Identity 1 -Values #{"Title" = "TitleUPDATE";"MMField"=$null}
Write-Host "-----------"
Make sure the field is not set as required as Mike suggested.

PowerShell to Export SharePoint Sites and Subsides with security groups

I'm attempting to come up with a powershell script that would allow me to export a list of sites and subsites and the permission groups there in to a CSV.
I'm familiar with using the cmdlts but not building whole scripts.
I'm able to use:
Get-SPOSiteGroup | Export-CSV C:\...
To export site groups to a CSV but it doesn't include the name of the sites they are in.
I also found a script online that would print out the sites and subsite in my site collection here:
https://sharepoint.stackexchange.com/questions/101176/powershell-to-list-all-sites-and-subsites-in-sharepoint-online
I'm not sure how to marry the information. I'm trying to export to a CSV a list of sites and subsites and the security groups there in.
I try to run:
get-sposite | Get-SPOSiteGroup **webdite**
And get this error message:
"Get-SPOSiteGroup : The input object cannot be bound to any parameters
for the command either because the command does not take pipeline
input or the input and its properties do not match any of the
parameters that take pipeline input"
I'm not sure how to get all of this to work together.
Get-SPOSiteGroup cmdlet accepts Site parameter, so site groups per every site collection within a tenant could be retrieved like this:
Connect-SPOService -Url $adminUrl
$sitesInfo = Get-SPOSite
#Retrieve and print all sites
foreach ($site in $sitesInfo) {
Write-Host 'Site collection:' $site.Url
Get-SPOSiteGroup -Site $site.Url
Write-Host '-----------------------------'
}
To retrieve in addition groups per every web site, the following script could be utilized:
$adminUrl = "https://<tenant>-admin.sharepoint.com"
$UserName = "<username>#<tenant>.onmicrosoft.com"
$Password = "--password goes here--"
$SecurePassword = $Password | ConvertTo-SecureString -AsPlainText -Force
$creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($UserName, $SecurePassword)
$pscreds = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $userName, $SecurePassword
Connect-SPOService -Url $adminUrl -Credential $pscreds
$sitesInfo = Get-SPOSite
foreach ($site in $sitesInfo) {
Write-Host 'Site collection:' $site.Url
#1. Retrieve and print site info
#Get-SPOSiteGroup -Site $site.Url
$AllWebs = Get-SPOWebs -Url $site.Url -Credential $creds
#2.Retrieve and print webs info (groups Title property in this case)
foreach ($web in $AllWebs) {
$web.Context.Load($web.RoleAssignments.Groups)
$web.Context.ExecuteQuery()
$web.RoleAssignments.Groups.GetEnumerator() | % { Write-Host $_.Title }
}
Write-Host '-----------------------------'
}
Key points:
to retrieve webs within a site collection Get-SPOWebs.ps1 is utilized
here
to get groups per web site Web.RoleAssignments.Groups is used

Update Sharepoint wiki page's aspx using powershell

I have been trying to take a manual step out of a process where I clone a wiki page in sharepoint (done via powershell) and then manually go to the aspx in sharepoint designer and update the textpart's default value:
EX:
<WpNs0:SPSlicerTextWebPart runat="server" MaximumCharacters="255" DefaultValue="REPLACETHISVALUE" RequireSelection="False" FilterMainControlWidthPixels="0" FilterName="Text Filter" Title="Text Filter" FrameType="BorderOnly" SuppressWebPartChrome="False" Description="Filters the contents of Web Parts by allowing users to enter a text value." ...
I'm using the following function for building the context for my copy, and I'm wondering if there is a way to pass the final ASPX site URL and manipulate the content:
function Get-SharepointContext
{
Param(
[Parameter(Mandatory=$true)]
$siteUrl,
[Parameter(Mandatory=$false)]
$cred)
If(!$cred){$cred = get-credential -UserName "$ENV:Username#$env:USERDNSDOMAIN" -Message "Login"}
[string]$username = $cred.UserName
$securePassword = $cred.Password
[Void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client")
$ctx = New-Object Microsoft.SharePoint.Client.ClientContext($siteUrl)
$ctx.RequestTimeOut = 1000 * 60 * 10;
$ctx.AuthenticationMode =[Microsoft.SharePoint.Client.ClientAuthenticationMode]::Default
$credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($username, $securePassword)
$ctx.Credentials = $credentials
$ctx.Load($ctx.Web)
$ctx.Load($ctx.Site)
$ctx.ExecuteQuery()
Return $ctx
}
Has anyone attempted this before or know of how I can actually do this?
We can change the web part properties using PnP PowerShell or CSOM code.
PnP:
#Get Current Context Site (Root)
$siteurl = "https://abc.sharepoint.com"
Connect-SPOnline -Url $siteurl
$ctx = Get-SPOContext
#Get Web Part ID
webpart = Get-SPOWebPart -ServerRelativePageUrl "/Pages/PnPPage.aspx" -Identity "Text Filter"
$webpartId = $webpart.Id
# Update WebPart
Set-SPOWebPartProperty -ServerRelativePageUrl "/Pages/PnPPage.aspx" -Identity $webpartId -Key Height -Value 500
CSOM:
function Change-WebPart {
#variables that needs to be set before starting the script
$siteURL = "https://spfire.sharepoint.com"
$userName = "mpadmin#spfire.onmicrosoft.com"
$webURL = "https://spfire.sharepoint.com"
$relativePageUrl = "/SitePages/Home.aspx"
# Let the user fill in their password in the PowerShell window
$password = Read-Host "Please enter the password for $($userName)" -AsSecureString
# set SharePoint Online credentials
$SPOCredentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($userName, $password)
# Creating client context object
$context = New-Object Microsoft.SharePoint.Client.ClientContext($webURL)
$context.credentials = $SPOCredentials
#get Page file
$page = $context.web.getFileByServerRelativeUrl($relativePageUrl)
$context.load($page)
#send the request containing all operations to the server
try{
$context.executeQuery()
}
catch{
write-host "Error: $($_.Exception.Message)" -foregroundcolor red
}
#use the WebPartManger to load the webparts on a certain page
$webPartManager = $page.GetLimitedWebPartManager([System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)
$context.load($webPartManager.webparts)
#send the request containing all operations to the server
try{
$context.executeQuery()
}
catch{
write-host "Error: $($_.Exception.Message)" -foregroundcolor red
}
#loop through all WebParts to get the correct one and change its property
foreach($webPartDefinition in $webpartmanager.webparts){
$context.Load($webPartDefinition.WebPart.Properties)
#send the request containing all operations to the server
try{
$context.executeQuery()
}
catch{
write-host "Error: $($_.Exception.Message)" -foregroundcolor red
}
#Only change the webpart with a certain title
if ($webPartDefinition.WebPart.Properties.FieldValues.Title -eq "Documents")
{
$webPartDefinition.webpart.properties["Title"] = "My Documents"
$webPartDefinition.SaveWebPartChanges()
}
}
}
Change-WebPart
Reference:
Update/Delete WebParts On SharePoint Pages Using PnP PowerShell
Editing Web Part properties with PowerShell CSOM in SharePoint

Powershell not getting SharePoint Online List

I'm trying to write a script for automatic VM Backups, that you can also start manually in SharePoint Online. I'm planning to keep a list with the names of the VMs in SharePoint and wanted to start writing the script by getting the list of VMs. I think my code looks good so far, but when I want to get the list by title it returns nothing.
Here's the code:
[Reflection.Assembly]::LoadFile(([System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client").location))
[Reflection.Assembly]::LoadFile(([System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.runtime").location))
Function Get-SPOContext([string]$Url,[string]$UserName,[string]$Password)
{
$SecurePassword = $Password | ConvertTo-SecureString -AsPlainText -Force
$context = New-Object Microsoft.SharePoint.Client.ClientContext($Url)
$context.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($UserName, $SecurePassword)
return $context
}
Function Get-ListItems([Microsoft.SharePoint.Client.ClientContext]$Context, [String]$ListTitle) {
$list = $Context.Web.Lists.GetByTitle($listTitle)
$qry = [Microsoft.SharePoint.Client.CamlQuery]::CreateAllItemsQuery()
$items = $list.GetItems($qry)
$Context.Load($items)
$Context.ExecuteQuery()
return $items
}
$UserName = read-host "Please enter your name:"
$PasswordReadHost = Read-Host -Prompt "Enter password" -AsSecureString
$Password = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($PasswordReadHost))
$Url = "https://domain.sharepoint.com/"
$ListTitle = "VMList"
$context = Get-SPOContext -Url $Url -UserName $UserName -Password $Password
$items = Get-ListItems -Context $context -ListTitle $ListTitle
When I run this, add a breakpoint at the end and check the value of the $list variable I get two error messages:
Exception calling "ExecuteQuery" with "0" argument(s): "The list
'VMList' does not exist on the website with the URL
'https://domain.sharepoint.com'.
and
An error occurred while enumerating through a collection: The
collection has not been initialized. It has not been requested or the
request has not been executed. It may need to be explicitly
requested.
After a lot of googling I tried changing many things, but nothing seemed to work. I guess my question is: Why can't the list be found on SharePoint and what does it mean to initialize a collection or if it's just an authorization issue?