I'm trying to check if file already exists in a SPO document library using PnP PowerShell command.

This is part of my PowerShell script:

Try {
    #Get all Files from the source folder
    $SourceFilesColl = $SourceFolder.Files

    #Iterate through each file and copy
    Foreach($SourceFile in $SourceFilesColl)
        #Get the source file
        $FileInfo = [Microsoft.SharePoint.Client.File]::OpenBinaryDirect($SourceFolder.Context, $SourceFile.ServerRelativeUrl)

        #Copy File to the Target location
        $TargetFileURL = $TargetFolder.ServerRelativeUrl+"/"+$SourceFile.Name
        Write-Host "Preparing checking file..."
        $checkFile = Get-PnPFile $TargetFileURL

        if($checkFile) {
            write-host "File already exists." -f Green
            write-host "File not exists." -f Red
            [COPY FILE CODE HERE...]

My code is working fine for first item of the foreach loop, but from the second iteration Get-PnPFile runs really slow (first time it takes 1-2 seconds to run, second time it takes about 5 minutes and it seems freezed) and at the end it return that "File not exists" even if the file exists.

I've already checked PnP PowerShell releases and I have installed the latest.

I've also checked $TargetFileURL but it has not special chars or something that could break the script. For example this is similar to the content of $TargetFileURL variable:

1st: "/sites/intranet/docs/my document.docx"
2nd: "/sites/intranet/docs/tech document.doc"

The only big difference is the file extension. Both filenames contains white spaces. I've also tried with the -ThrowExceptionIfFileNotFound parameter in Get-PnPFile command (obviously I put it in a try-catch block), but nothing changed.

Any suggestion?


1 Answer 1


Try this:

$checkFile = Get-PnPFile $TargetFileURL **-AsListItem**

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.