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

2 answers

  • answered 2020-06-02 20:47 Adam

    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 :)

  • answered 2020-06-03 09:17 Jerry_MSFT

    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
    
    }