Powershell not getting SharePoint Online List - powershell

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?

Related

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

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.

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...

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

Create Folder in DocLib of a Teamsite - Office 365 - Sharepoint Online

I want to create an example folder in a Document Library of a created Teamsite on Sharepoint Online using Powershell but am running into an error.
After I have created the Teamsite I use the following script:
#Retrieve list
$DocLibName = "Dokumente"
$FolderTitle = "Beispiel"
$List = $ctx.Web.Lists.GetByTitle($DocLibName)
$folder = $list.AddItem("", [Microsoft.SharePoint.SPFileSystemObjectType]::Folder)
$folder["Title"] = $FolderTitle
$folder.Update();
$ctx.Load($List)
$ctx.ExecuteQuery()
Error Message
The type [Microsoft.SharePoint.SPFileSystemObjectType] was not found : Make sure that the assembly that contains this type is loaded.
Line:79 Char:1
+ $ Folder = $ List.addItem ("" [Microsoft.SharePoint.SPFileSystemObjectType ] :: Folde ...
It is not possible to use an index to a null array.
Line:80 Char:1
+ $ Folder ["Title"] = $FolderTitle
It is not possible to call a method for an expression of the NULL .
Line:81 Char:1
+ $Folder.Update();
How can this be resolved?
You are getting this error since Microsoft.SharePoint.SPFileSystemObjectTypetype belongs to SharePoint Server Side API which is not compatible with Office 365.
Below is demonstrated how to create a folder in SharePoint Online site via PowerShell (utilizes SharePoint CSOM API)
Function Create-Folder()
{
Param(
[Parameter(Mandatory=$True)]
[Microsoft.SharePoint.Client.Folder]$ParentFolder,
[Parameter(Mandatory=$True)]
[String]$FolderName
)
$folder = $ParentFolder.Folders.Add($folderName)
$ParentFolder.Context.Load($folder)
$ParentFolder.Context.ExecuteQuery()
return $folder
}
Function Get-Context($Url,$Username,$Password){
$SecurePassword = $Password | ConvertTo-SecureString -AsPlainText -Force
$credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($UserName, $SecurePassword)
$ctx = New-Object Microsoft.SharePoint.Client.ClientContext($url)
$ctx.Credentials = $credentials
return $ctx
}
Usage
$Url = "https://contoso.sharepoint.com/"
$UserName = "jdoe#contoso.onmicrosoft.com"
$Password = ""
$TargetFolderName = "Archive2016"
$ctx = Get-Context -Url $Url -Username $Username -Password $Password
$parentFolder = $ctx.Web.Lists.GetByTitle("Documents").RootFolder
$folder = Create-Folder -ParentFolder $parentFolder -FolderName $TargetFolderName
Write-Host "Folder [$TargetFolderName] has been created succesfully. Url: $($folder.ServerRelativeUrl)"
For creating a folder hierarchy the following script could be utilized:
Function Create-FolderHierarchy()
{
Param(
[Parameter(Mandatory=$True)]
[Microsoft.SharePoint.Client.Folder]$ParentFolder,
[Parameter(Mandatory=$True)]
[String]$FolderUrl
)
$folderNames = $FolderUrl.Trim().Split("/",[System.StringSplitOptions]::RemoveEmptyEntries)
$folderName = $folderNames[0]
$curFolder = $ParentFolder.Folders.Add($folderName)
$ParentFolder.Context.Load($curFolder)
$ParentFolder.Context.ExecuteQuery()
if ($folderNames.Length -gt 1)
{
$curFolderUrl = [System.String]::Join("/", $folderNames, 1, $folderNames.Length - 1)
return Create-FolderHierarchy -ParentFolder $curFolder -FolderUrl $curFolderUrl
}
return $curFolder
}
If you are interested in scenario for uploading files while preserving a folder structure, take a look at How to: Upload files into Office 365 via PowerShell post, it contains ready made script for that purpose.