How to use Get-PnPFolder to show SharePoint folder perm - powershell

I am using PowerShell PNP to try and read the permissions of a folder but the command Get-PnPFolder does not appear to include the permissions.
I tried the code listed here but the permissions collection are empty. https://sharepoint.stackexchange.com/questions/221118/retrieve-permissions-at-folder-and-file-level-in-powershell/221513 . This small sample below is what I used for testing.
$spserver = 'https://myportal.sharepoint.com/sites/mysite/'
Connect-PnPOnline –Url $spserver –UseWebLogin
$foldername = 'myFormLibraryName'
$folderObj = Get-PnPFolder -Url $foldername -Includes ListItemAllFields.RoleAssignments, ListItemAllFields.HasUniqueRoleAssignments
$folderObj.ListItemAllFields.HasUniqueRoleAssignments
$folderObj.ListItemAllFields.RoleAssignments
The results of the code will return "collection has not been initialized". How do I get a list of the permissions for a SharePoint folder?

I was not able to get the code to work with Get-PnPFolder and used the code below as an alternative.
$spserver = 'https://myportal.sharepoint.com/sites/mysite/'
Connect-PnPOnline –Url $spserver –UseWebLogin
$ctx=Get-PnPContext
$foldername = 'Documents'
$web = $ctx.Web
$list = $ctx.Site.RootWeb.Lists.GetByTitle($foldername)
$ctx.Load($list)
$ctx.ExecuteQuery()
Write-Host 'count is ' $list.ItemCount
$roleass = $list.RoleAssignments
$ctx.Load($roleass)
$ctx.ExecuteQuery()
Write-Host 'loaded'
foreach($rol in $roleass) {
$ctx.Load($rol.Member)
$ctx.ExecuteQuery()
Write-Host $rol.Member.Title
}

Related

Downloading SharePoint online list items' attachments locally will not allow me to open those files (seems the file are corrupted)

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

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
}

Problem with code in Sharepoint/Powershell

So here's my problem,
We want to automate the copy of notepad (Sharepoint) in my company,
We already have the power-automate script which allows us to copy links from sharepoint sites,
And here is the Power shell code which allows you to recover the site files and copy them to another:
$SiteURL = "https://******.sharepoint.com/sites/********"
$TargetFolderURL = "/sites/*********/*****"
$SitestoCopy = "copy"
Connect-PnPOnline -Url $SiteURL -UseWebLogin
$items = Get-PnPListItem -List $SitestoCopy
Write-Host "Nombre total d'éléments :" $items.Count
ForEach ($item in $items)
{
Write-Host $item["Title"]
#Copy All Files and Folders from one folder to another
Copy-PnPFile -SourceUrl $item["Title"] -TargetUrl $TargetFolderURL -SkipSourceFolderName -Force
}
I have an error : Copy-PnPFile : File not found.
i have no clue to resolve this problem,
Anyone could help me?
Thank you
I think the problem is in the -SourceUrl param. You pass the item Title. According to the spec this should be the relative url to the item. I am not sure now in what column it was stored I am guessing something like "ServerRelativeUrl" or "FileRef". Please try to check it out and change it to correct column to pass the url to the item not the title.
I hope it will be of any help :)
SourceUrl should be the file server relative url, use FileRef instead,
TargetUrl should be TargetFolderURL +filename
Modify the code snippet as below:
$SiteURL = "https://Tenant.sharepoint.com/sites/dev"
$TargetFolderURL = "/sites/dev/docs/"
$SitestoCopy = "copy"
Connect-PnPOnline -Url $SiteURL -UseWebLogin
$items = Get-PnPListItem -List $SitestoCopy
Write-Host "Nombre total d'éléments :" $items.Count
ForEach ($item in $items)
{
$TargetFileUrl=$TargetFolderURL+$item["FileLeafRef"]
#Copy All Files and Folders from one folder to another
Copy-PnPFile -SourceUrl $item["FileRef"] -TargetUrl $TargetFileUrl -SkipSourceFolderName -Force
}

Getting 'created by' for a folder in Sharepoint document library

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"]
}

powershell script to Check if a folder exist in SharePoint with CSOM

I have a powershell script which i got somewhere from the internet that creates a folder in SharePoint. It works as it can create a folder when i tested it but, i would like like to know how can i modify this script to check if the folder that i am creating does not exist yet? can someone please help?
function CreateFolder {
param
(
$SPSite,
$SiteUrl,
$FolderName,
$User,
$Password
)
$ErrorActionPreference = "Stop"
$DocLibName = "Documents"
$FullSPPath = $SPSite+ $SiteUrl
#Connect Office 365 SharePoint Online Site
$Context = New-Object Microsoft.SharePoint.Client.ClientContext($SPSite)
$Creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($User,$Password)
$Context.Credentials = $Creds
$List = $Context.Web.Lists.GetByTitle($DocLibName)
$Context.Load($List)
#Get the List Root Folder
$ParentFolder=$Context.web.GetFolderByServerRelativeUrl($FullSPPath)
#Create New Folder
$Folder = $ParentFolder.Folders.Add($FolderName)
$ParentFolder.Context.Load($Folder)
$ParentFolder.Context.ExecuteQuery()
Write-host "New Folder Created Successfully!"
}
You can do pretty much the same as what you are doing to get the rootfolder. So if the new folder is called NewFolder in the root of your library it would look like:
$newFolder = $Context.Web.GetFolderByServerRelativeUrl("/sites/site/library/NewFolder")
$context.Load($newFolder)
$context.ExecuteQuery()
Now all you need to do is check the exists property on the Folder object:
if (!$newFolder.Exists) {
#do stuff here
}