Below C# code I have used to update the folder property in shared document, same concept I have tried in PowerShell but I didn't get any clue.
SPFolder newFolder = folders.Add(ParentURL + FolderURL + "/" + FolderName);
//Added Title Property to newFolder
newFolder.AddProperty("vti_title", FolderName);
//newFolder.Update();
In PowerShell:
> $web = Get-SPWeb "http://server/sites/4tmdk9h7qc4g"
> $site=$web $list = $web.Lists["Shared Documents"]
foreach ($item in $list.Folders)
{
write-host $item["Title"]
/?? HOW TO UPDATE HERE
$item.Update()
}
$item is a SPListItem object. Use SPListItem.Folder to access the SPFolder object:
$item.Folder
Finally this code loop all the site document folder and updated the title
$inputUrl =Read-Host "Enter the site URL"
$site = Get-SPSite -identity $inputUrl
$site | Get-SPWeb -limit |ForEach-Object
{
$web = Get-SPWeb $_.Url
$list =$web.lists["Shared Documents"]
Write-Host $_.Url
foreach($item in $list.folders)
{
$item["Title"]="ayyappan"
$item.update()
Write-Host $item["Title"]
}
}
Related
I have a SharePoint online list , and this list contain items with attachments. so i want to download all the list item attachems. so i wrote this PnP Power Shell sript:-
$ApprovalListItems = Get-PnPListItem -List "tickets" -PageSize 1000 -ScriptBlock { Param($items) $items.Context.ExecuteQuery()} | ForEach-Object {
$ctx = Get-PnPContext
$spSourceWeb= Get-PnPWeb
$ItemAttachmentURLPrefix = 'https://****.sharepoint.com/Lists/tickets/Attachments/'+$_['ID']+'/'
$attachmentCollection = ForEach-Object{Get-PnPProperty -ClientObject $_ -Property "AttachmentFiles"}
$AttachmentSeq = 0
ForEach($Attachment in $attachmentCollection)
{
Write-Host "`tDownloading Attachement: " $attachment $ItemAttachmentURLPrefix
$AttachmentSeq++
$AttachmentDataObj = "" | Select "Attachment Seq", "JDE Company", "Vendor Number", "Vendor Invoice Number", "Attachment Name", "Attachment System Name", "Job-run Date/Time Stamp"
Write-Host $Attachment.FileName
$file = Get-PnPFile -Url ($ItemAttachmentURLPrefix + $Attachment.FileName)
$bytes = (Get-PnPFile -Url ($ItemAttachmentURLPrefix + $Attachment.FileName)).OpenBinaryStream()
$name = "C:\Attachments\"+$Attachment.FileName
$fs = New-Object System.IO.StreamWriter($name, "OpenOrCreate")
$fs.Write($bytes, 0 , $bytes.Length)
$fs.Close()
$stream = $streamResult.Value
Write-Host $file.Name
Write-Host $stream.Name
}
}
but the files that will get saved can not be opened, for example this excel sheet will raise this error:-
while a pdf will raise this error:-
any advice what is wrong with my script?
Thanks
Use PnP PowerShell code in below format to download list item attachments to local folder:
Connect-PnPOnline -Url https://contoso.sharepoint.com/sites/dev -Interactive
$listitem = Get-PnPListItem -List Employee -Id 2
$attachments = ForEach-Object {Get-PnPProperty -ClientObject $listitem -Property "AttachmentFiles"}
$attachments | ForEach-Object { Get-PnPFile -Url $_.ServerRelativeUrl -FileName $_.FileName -Path "E:\SharePoint\Documents" -AsFile }
Source: Read items attachments and write them to local folder
I have been using the following to output as a CSV a SharePoint Online document library, including all custom metadata field properties.
I however cannot obtain the assigned Content Type. I am treating as a standard column, but imagine there is more to it? I don't seem to be able to find anything relevant.
#Parameters
$SiteURL = "https://SHAREPOINT URL"
$ListName= "LIBRARYNAME"
$ReportOutput = "C:\LOCATION.csv"
$Pagesize = 500
#Connect to SharePoint Online site
Connect-PnPOnline $SiteURL -UseWebLogin
#Delete the Output report file if exists
If (Test-Path $ReportOutput) { Remove-Item $ReportOutput}
#Array to store results
$Results = #()
#Get all Documents from the document library
$List = Get-PnPList -Identity $ListName
$global:counter = 0;
$ListItems = Get-PnPListItem -List $ListName -PageSize $Pagesize -Fields Author, Editor, Created, File_x0020_Type, Business_x0020_Unit, Department, Device, Document_x0020_Type, Employee_x0020_Status, Retention_x0020_Period, Scan_x0020_Date, Scanned_x0020_by, Staff_x0020_ID, Staff_x0020_Name, ContentType -ScriptBlock `
{ Param($items) $global:counter += $items.Count; Write-Progress -PercentComplete ($global:Counter / ($List.ItemCount) * 100) -Activity `
"Getting Documents from Library '$($List.Title)'" -Status "Getting Documents data $global:Counter of $($List.ItemCount)";} | Where {$_.FileSystemObjectType -eq "File"}
$ItemCounter = 0
#Iterate through each item
Foreach ($Item in $ListItems)
{
$Results += New-Object PSObject -Property ([ordered]#{
Name = $Item["FileLeafRef"]
Type = $Item.FileSystemObjectType
FileType = $Item["File_x0020_Type"]
RelativeURL = $Item["FileRef"]
CreatedByEmail = $Item["Author"].Email
CreatedOn = $Item["Created"]
Modified = $Item["Modified"]
ModifiedByEmail = $Item["Editor"].Email
BusinessUnit = $Item["Business_x0020_Unit"]
Department = $Item["Department"]
Device = $Item["Device"]
DocumentType = $Item["Document_x0020_Type"]
EmployeeStatus = $Item["Employee_x0020_Status"]
RetentionPeriod = $Item["Retention_x0020_Period"]
ScanDate = $Item["Scan_x0020_Date"]
ScannedBy = $Item["Scanned_x0020_by"]
StaffID = $Item["Staff_x0020_ID"]
StaffName = $Item["Staff_x0020_Name"]
ContentType = $Item["ContentType"]
})
$ItemCounter++
Write-Progress -PercentComplete ($ItemCounter / ($List.ItemCount) * 100) -Activity "Exporting data from Documents $ItemCounter of $($List.ItemCount)" -Status "Exporting Data from Document '$($Item['FileLeafRef'])"
}
#Export the results to CSV
$Results | Export-Csv -Path $ReportOutput -NoTypeInformation
Write-host "Document Library Inventory Exported to CSV Successfully!"
Any pointers on how I can capture the involved Content Type of the library items welcomed!
Try this:
$ctx = Get-PnPContext
Foreach ($Item in $ListItems)
{
$Ctx.Load($Item.ContentType)
$Ctx.ExecuteQuery()
write-host $Item.ContentType.Name
}
Test result:
Updated:
$ctx = Get-PnPContext
Foreach ($Item in $ListItems)
{
$Ctx.Load($Item.ContentType)
$Ctx.ExecuteQuery()
$Results += New-Object PSObject -Property ([ordered]#{
Name = $Item["FileLeafRef"]
Type = $Item.FileSystemObjectType
FileType = $Item["File_x0020_Type"]
RelativeURL = $Item["FileRef"]
CreatedByEmail = $Item["Author"].Email
CreatedOn = $Item["Created"]
Modified = $Item["Modified"]
ModifiedByEmail = $Item["Editor"].Email
BusinessUnit = $Item["Business_x0020_Unit"]
Department = $Item["Department"]
Device = $Item["Device"]
DocumentType = $Item["Document_x0020_Type"]
EmployeeStatus = $Item["Employee_x0020_Status"]
RetentionPeriod = $Item["Retention_x0020_Period"]
ScanDate = $Item["Scan_x0020_Date"]
ScannedBy = $Item["Scanned_x0020_by"]
StaffID = $Item["Staff_x0020_ID"]
StaffName = $Item["Staff_x0020_Name"]
ContentType = $Item.ContentType.Name
})
I want to get the author(who created) a folder in a Sharepoint Online using PnP PowerShell. The time last modified I can get it, but the field author I cannot get it. I know that can be two different fields, author and modifier, but I cannot get any from this.
For the folders:
$folder = Get-PnPFolderItem -FolderSiteRelativeUrl $folderPath -ItemName $subfolderName
Write-Host "URL : " $folder.ServerRelativeUrl
Write-Host "Name : " $folder.Name
Write-Host "Modified : " $folder.TimeLastModified
# above are ok, but $folder has no author property
# same next line fails, Author it does not exist
$folder= Get-PnPFolder -Url "$folderPath/$subfolderName" -Includes ListItemAllFields.Author
For the files, is easy I use:
Get-PnPFile -ServerRelativeUrl $file.ServerRelativeUrl -Path $destinationfolder -FileName $file.Name -AsFile
$f = Get-PnPFile -Url "$($folderUrl)/$($file.Name)" -AsListItem
$fileDetails = #{
File = "$($destinationFolder)/$($file.Name)"
Author = $f["Author"].Email
Created = $f["Created"]
}
I just find the solution, if anyone need:
context = Get-PnPContext
$context.load($context.Web)
$context.ExecuteQuery()
$list = $context.Web.Lists.GetByTitle("Documente")
$context.Load($list)
$context.ExecuteQuery()
$camlQuery = New-Object Microsoft.SharePoint.Client.CamlQuery
$camlQuery.ViewXml ="<View Scope='RecursiveAll'><Query><Where><Eq><FieldRef Name='FileRef' /><Value Type='Text'>/server/folder/relativepath</Value></Eq></Where></Query></View>";
$allItems=$list.GetItems($camlQuery)
$context.Load($allItems)
$context.ExecuteQuery()
foreach($item in $allItems){
Write-Host "##############"
Write-Host $item["FileRef"]
$item["Author"].Email
$item["Modified"]
}
I am running the following to get all views for all lists in all subsites of our Sharepoint installation.
$views = #()
foreach ($web in Get-PnPSubWebs) {
foreach ($list in Get-PnPList -Web $web.id) {
foreach ($view in Get-PnPView -list $list.id -web $web.id) {
$views += [pscustomobject]#{Id = $view.Id; StyleId = $view.StyleId}
}
}
}
Which works fine, I am getting all views as expected. But I have not been successful in setting a new style for the views.
I have tried to use $view.ApplyStyle() as is described here: https://social.msdn.microsoft.com/forums/sharepoint/en-US/58068fb4-33ad-46cf-b866-bd86e1cbcafb/update-sharepoint-list-view-style-via-powershell and here: http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spview.applystyle.aspx.
I however get the following error:
Method invocation failed because [Microsoft.SharePoint.Client.View] does not contain a method named 'ApplyStyle'.
Next I tried Set-PnPView -Web $web.id -List $list.id -Identity $view.Id -Values #{StyleId=17} per these instructions:
https://learn.microsoft.com/en-us/powershell/module/sharepoint-pnp/set-pnpview?view=sharepoint-ps. That only got me this message:
WARNING: Setting property 'StyleId' to '17' failed with exception 'Property set method not found.'. Value will be ignored.
And as a last resort $view.StyleId = 17 does also not work. Then I get this: 'StyleId' is a ReadOnly property. as expected.
We want to have our lists all be in the shaded style (id:17). We have hundreds of lists and since I'm hoping there is a better way then spending a full day manually changing them all. I have yet to find a way to change the default list view style but all our lists seem to be set to "default" view although there isn't a way to see what the default style is or change it.
All suggestions appreciated.
Update:
This is the complete script that I ended up using for all views in all lists in all subwebs of our main site:
Connect-PnPOnline –Url http://sharepointsite –CurrentCredentials
foreach ($web in Get-PnPSubWebs) {
foreach ($list in Get-PnPList -Web $web.id) {
foreach ($view in Get-PnPView -list $list.id -web $web.id) {
[xml]$Doc = New-Object System.Xml.XmlDocument
$Doc.LoadXml($view.ListViewXml);
$element = $Doc.SelectSingleNode("//View//ViewStyle");
if ($element -eq $null)
{
$element = $Doc.CreateElement("ViewStyle");
$element.SetAttribute("ID", 17);
$Doc.DocumentElement.AppendChild($element);
}
else
{
$element.SetAttribute("ID", 17);
}
Set-PnPView -Web $web.id -List $list.id -Identity $view.Id -Values #{ListViewXml=$Doc.FirstChild.InnerXml}
}
}
}
And then to get all lists for out main web as well I ran this:
Connect-PnPOnline –Url http://sharepointsite –CurrentCredentials
$web = Get-PnPWeb
foreach ($list in Get-PnPList -Web $web.id) {
foreach ($view in Get-PnPView -list $list.id -web $web.id) {
[xml]$Doc = New-Object System.Xml.XmlDocument
$Doc.LoadXml($view.ListViewXml);
$element = $Doc.SelectSingleNode("//View//ViewStyle");
if ($element -eq $null)
{
$element = $Doc.CreateElement("ViewStyle");
$element.SetAttribute("ID", 17);
$Doc.DocumentElement.AppendChild($element);
}
else
{
$element.SetAttribute("ID", 17);
}
Set-PnPView -Web $web.id -List $list.id -Identity $view.Id -Values #{ListViewXml=$Doc.FirstChild.InnerXml}
}
}
Here is my sample test script for your reference(I tested in online, I think it should works for SharePoint 2019 as it's CSOM api).
Add-Type -Path (Resolve-Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll")
Add-Type -Path (Resolve-Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll")
$UserName = "Wendy#tenant.onmicrosoft.com"
$siteURL = "https://tenant.sharepoint.com/sites/lee"
$Password = "password"
[SecureString]$SecurePass = ConvertTo-SecureString $Password -AsPlainText -Force
$Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Username, $SecurePass)
$ctx = New-Object Microsoft.SharePoint.Client.ClientContext($siteURL)
$ctx.credentials = $Credentials
try{
$list = $ctx.web.Lists.GetByTitle("MyList2")
$views = $list.views
$ctx.load($views)
$ctx.executeQuery()
foreach ($v in $views)
{
if ($v.Title -eq "All Items")
{
$ctx.Load($v);
$ctx.ExecuteQuery();
[xml]$Doc = New-Object System.Xml.XmlDocument
$Doc.LoadXml($v.ListViewXml);
$element = $Doc.SelectSingleNode("//View//ViewStyle");
if ($element -eq $null)
{
$element = $Doc.CreateElement("ViewStyle");
$element.SetAttribute("ID", 17);
$Doc.DocumentElement.AppendChild($element);
}
else
{
$element.SetAttribute("ID", 17);
}
$v.ListViewXml = $Doc.FirstChild.InnerXml;
$v.Update();
$ctx.ExecuteQuery();
}
}
}
catch{
write-host "$($_.Exception.Message)" -foregroundcolor red
}
I'm trying to write a powershell script to go through all the sub sites in a site collection and remove a node that is no longer required.
I've placed my script below - but I'm getting an error on Get-SPWeb : The pipeline has been stopped - I'm thinking I may need to set a parameter to stop the pipe being closed? Any help is awesome!
$site = Get-SPSite http://sitecollurl
$site | get-spweb -limit all | foreach-object{
$webURL = $_.url
$web = Get-SPWeb $webURL
$navigationNodes = $web.Navigation.QuickLaunch
ForEach ($Node in $NavigationNodes)
{
if($node.Title -eq "My User Profile")
{
$node.Delete()
}
}
$web.Dispose()
}
I just came across this issue so thought I would share, note in my case it was to remove all QuickLaunch menu Items titled "Libraries" if it had no children:
Get-SPSite http://sitecollectionurl | get-spweb -limit all | foreach-object{
$webURL = $_.url
$web = Get-SPWeb $webURL
$pubWeb = [Microsoft.Sharepoint.Publishing.PublishingWeb]::GetPublishingWeb($Web)
$qlNav = $pubWeb.Navigation.CurrentNavigationNodes
$qlHeading = $qlNav | where { $_.Title -eq "Libraries" }
$qlLibraries = $qlHeading.Children
if($qlLibraries.Count -eq 0)
{
$qlHeading.delete()
}
else
{
$qlLibraries | Select Title,ID
$count = $qlLibraries.Count
write-host "Other Libraries are listed on $url. Count = $count"
}
$pubWeb.Update()
$web.Dispose
}
Obviously replace http://sitecollectionurl with your own site collection URL, and libraries with whatever title you are trying to remove.
Dan