Update Sharepoint wiki page's aspx using powershell - 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

Related

SharePoint Online Sign in and password does not match issue in PowerShell

I'm trying to connect to SharePoint Online but I'm getting this error and not 100% sure why so I would be really appreciated if I can get any help or suggestion why it might be.
I believe it might have to do with my tenant using MFA so just wondering how can I connect/login using MFA?.
#Variables
$SiteURL = "https://companyName-my.sharepoint.com/personal/yzqpsn_nam_corp_m_com"
$ServerRelativeUrl= "documents/Testing"
Try {
#Get Credentials to connect
$Cred= Get-Credential
#Setup the context
$Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$Ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)
#Get the web from URL
$Web = $Ctx.web
$Ctx.Load($Web)
$Ctx.executeQuery()
#Get the Folder object by Server Relative URL
$Folder = $Web.GetFolderByServerRelativeUrl($ServerRelativeUrl)
$Ctx.Load($Folder)
$Ctx.ExecuteQuery()
#Call the function to empty Folder
Empty-SPOFolder $Folder
#Delete the given Folder itself
Write-host -f Green "Deleting Folder:"$Folder.ServerRelativeUrl
$Folder.Recycle() | Out-Null
$Ctx.ExecuteQuery()
}
Catch {
write-host -f Red "Error:" $_.Exception.Message
}

Sharepoint PnP List: How to "Group by" columns using 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

Use powershell to delete Sharepoint online list item

I currently have a powershell script to loop through a list on an Sharepoint online site.
$creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials("[USERNAME]", (ConvertTo-SecureString "[PASSWORD]" -AsPlainText -Force))
$ctx = New-Object Microsoft.SharePoint.Client.ClientContext("https://[SITENAME].sharepoint.com/sites/Projekter")
$ctx.credentials = $creds
try{
$lists = $ctx.web.Lists
$list = $lists.GetByTitle("Ekstern synkronisering")
$listItems = $list.GetItems([Microsoft.SharePoint.Client.CamlQuery]::CreateAllItemsQuery())
$ctx.load($listItems)
$ctx.executeQuery()
foreach($listItem in $listItems)
{
$internal = $listItem["ConnectionString1"]
$external = $listItem["ConnectionString2"]
$folder = $listItem["Mappe"]
$project = $listItem["Project"]
$caseNo = $listItem["Title"]
$doc = New-Object System.Xml.XmlDocument
$doc.Load("C:\Script\PS-Layer2\xmlTemplate.xml")
$ns = New-Object System.Xml.XmlNamespaceManager($doc.NameTable)
$ns.AddNamespace("ns", $doc.DocumentElement.NamespaceURI)
$doc.SelectSingleNode("//ns:dataEntity[#name='Intern site']", $ns).connectionString = $internal+";Authentication=Office365;User Id=$userId;Password=$pwd;"
$doc.SelectSingleNode("//ns:dataEntity[#name='Externt site']", $ns).connectionString = $external+";Authentication=Office365;User Id=$userId;Password=$pwd;"
$doc.Save("C:\Temp\$caseNo - $project - $folder.xml")
}
}
catch{
write-host "$($_.Exception.Message)" -foregroundcolor red
}
This works fine to get the items and modify an XML file..
What I would like to do is, when the XML file has been created, it shall delete the listitem from the sharepoint site, so that it will not be created on the next run again.
Does anyone have a solution on that?
Best regards...

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?

Uploading file and inserting information to custom columns to a Sharepoint Library using Powershell

I'm learning powershell to create a script that uploads files to a sub-site library inside SharePoint. I managed to get it working and uploading .doc files to my library, however I also want fill in any metadata specified in additional columns with the file at the same time. I'm not using the SharePoint snap-in and instead using the webclient functions. Here is the simple powershell script
# create the Variable Path and Pass the source folder path
$path = "THE FILE"
# create the Variable destination and pass the URL of the SharePoint List
$destination = "SharePoint SubSite"
# Store the current user default credentials in the Variable Credentials
$credentials = [System.Net.CredentialCache]::DefaultCredentials;
# Create the object of the Webclient
$webclient = New-Object System.Net.WebClient;
$webclient.Credentials = $credentials;
$webclient.UploadFile($destination + “/” + "Filename", “PUT”, TheFile)
This code works however I don't know how to use the webclient functions to pass metadata to custom columns. When the file is uploaded I noticed the only first two columns are updated but the custom fields are left blank.
If this is even possible let me know.
Much thanks for your help
Basically three options are available here (it is assumed SharePoint 2010 is used):
consume SharePoint 2010 REST interface
consume SharePoint Web Services
consume SharePoint 2010 Client SDK
How to consume SharePoint 2010 REST Interface via PowerShell
The following function demonstrates how to perform CRUD operations using SharePoint 2010 REST interface:
<#
.Synopsis
Sends an HTTP or HTTPS request to a SharePoint 2010 REST-compliant web service.
.DESCRIPTION
This function sends an HTTP or HTTPS request to a Representational State
Transfer (REST)-compliant ("RESTful") SharePoint Online web service.
.EXAMPLE
Invoke-SPRestMethod -Url "https://contoso.sharepoint.com/_vti_bin/ListData.svc/Projects"
#>
Function Invoke-SPRestRequest()
{
Param(
[Parameter(Mandatory=$True)]
[String]$WebUrl,
[Parameter(Mandatory=$True)]
[String]$ListName,
[Parameter(Mandatory=$False)]
[int]$ItemId,
[Parameter(Mandatory=$False)]
[String]$QueryOptions,
[Parameter(Mandatory=$False)]
[Microsoft.PowerShell.Commands.WebRequestMethod]$Method = [Microsoft.PowerShell.Commands.WebRequestMethod]::Get,
[Parameter(Mandatory=$False)]
[System.Net.ICredentials]$Credentials,
[Parameter(Mandatory=$False)]
[String]$Payload,
[Parameter(Mandatory=$False)]
[String]$ETag,
[Parameter(Mandatory=$False)]
[String]$XHTTPMethod,
[Parameter(Mandatory=$False)]
[System.String]$Accept = "application/json;odata=verbose",
[Parameter(Mandatory=$False)]
[String]$ContentType = "application/json;odata=verbose"
)
#Construct Endpoint URL
$endpointUrl = $WebUrl + "/_vti_bin/listdata.svc/" + $ListName
if($ItemId){
$endpointUrl = $endpointUrl + "(" + $ItemId + ")"
}
if($QueryOptions){
$endpointUrl = $endpointUrl + $QueryOptions
}
$client = New-Object System.Net.WebClient
if($Credentials) {
$client.Credentials = $Credentials
}
$client.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f")
$client.Headers.Add("Content-Type",$ContentType)
$client.Headers.Add("Accept",$Accept)
if($Method -eq "Get") {
$result = $client.DownloadString($endpointUrl) | ConvertFrom-Json
}
elseif ($Method -eq "Post") {
if($ETag) {
$client.Headers.Add("If-Match", $ETag)
}
if($XHTTPMethod) {
$client.Headers.Add("X-HTTP-Method", $XHTTPMethod)
}
if($Payload) {
$client.UploadString($endpointUrl,$Method,$Payload)
}
else {
$client.UploadString($endpointUrl,$Method)
}
}
$client.Dispose()
return $result
}
Gist: Invoke-SPRestRequest.ps1
Example
The following example demonstrates how to upload a file into SharePoint 2010 and set metadata properties. It consists of:
Upload a file operation
Find the uploaded list item associated with uploaded file
Update list item properties
Code:
$UserName = "username"
$Password = Read-Host -Prompt "Enter the password"
$WebUrl = "https://contoso.sharepoint.com/project"
$FolderUrl = "/project/Shared Documents/Archive"
Function Find-ListItem([string]$WebUrl,[System.Net.ICredentials]$Credentials,[string]$ListName,[string]$QueryOptions)
{
$result = Invoke-SPRestRequest -WebUrl $WebUrl -ListName $ListName -QueryOptions $QueryOptions -Credentials $Credentials
return $result.d.results
}
Function Update-ListItem([string]$WebUrl,[System.Net.ICredentials]$Credentials,[string]$ListName,[int]$ItemId)
{
$itemPayload = #{
"DocumentStatusValue" = "Close";
} | ConvertTo-Json
Invoke-SPRestRequest -WebUrl $WebUrl -ListName $ListName -ItemId $ItemId -Credentials $Credentials -Method Post -Payload $itemPayload -ETag "*" -XHTTPMethod "MERGE"
}
Function Upload-File([string]$WebUrl,[System.Net.ICredentials]$Credentials,[string]$FolderUrl, [string]$FileName)
{
$client = New-Object System.Net.WebClient
#$client.Credentials = $Credentials
$client.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f")
$siteUri = New-Object Uri($WebUrl)
$fileUri = New-Object Uri($siteUri, ($FolderUrl + "/" + [System.IO.Path]::GetFileName($FileName)))
$result = $client.UploadFile($fileUri, "PUT", $FileName)
$client.Dispose()
}
#1.Upload a File
Upload-File -WebUrl $WebUrl -FolderUrl $FolderUrl -FileName "D:\tmp\SharePoint User Guide.docx"
#2.Find an associated List Item for a File
$query = "?`$filter=Path eq '" + $FolderUrl + "'"
$ListItem = Find-ListItem -WebUrl $WebUrl -ListName "Documents" -QueryOptions $query
#3.Update List Item properties
Update-ListItem -WebUrl $WebUrl -ListName "Documents" -ItemId $ListItem.Id
References
SharePoint Foundation REST Interface