Will Holland is a Senior Software Engineer at ThreeWill. Will has proven to be adept at understanding a client’s needs and matching them with the appropriate solution. Recently he’s developed a passion for working with .NET, MVC, and cloud-based solutions such as Microsoft Azure and Office 365.
Setting the Stage
TLDR – Learn about why you should use Remove-PnPListItem vs Remove-PnPFile…
In recent years, I’ve come to relish opportunities to script out processes using PowerShell. As much as we here at ThreeWill deal with SharePoint Online, becoming familiar with PowerShell was born of necessity. It wasn’t always pleasant, but I did eventually achieve a level of comfort.
Fortunately for us all, that comfort level skyrocketed with the introduction of the SharePoint Patterns & Practices’ PowerShell commands. These powerful commands tremendously reduced the complexity of working with the client-side object model (CSOM) to interact with SharePoint and have made my script writing (and life) much easier.
But, as with any good story, any period of extended comfort must inevitably be spoiled by a tragic event.
(queue dramatic music)
Enter the Villain
As a part of an automated archival script, I needed to calculate the name of a PDF file to archive from various fields on a related list item the script had just archived. Once the PDF had been archived, I used the Remove-PnPFile command to remove the original PDF from the source location…like so:
Remove-PnPFile –SiteRelativeUrl “PDF Library/$FileName” –Force
To explain, “PDF Library” is the name of the document library. If the value of $FileName was ‘FOO.pdf’, this command would delete the file located at https://contoso.sharepoint.com/sites/mysite/PDF Library/Foo.pdf
Unfortunately, in one instance, the value of $FileName was a null value. I assumed this wasn’t possible…but we all know the saying.
The end result was as unexpected as the results of my assumption. Rather than Remove-PnPFile throwing an error about an invalid URL, or no file found, it simply deleted the ENTIRE LIBRARY.
The Final Act
Fortunately for me, the deleted library was just a standard document library that had no content. If that had not of been the case, this story might not have such a happy ending, as the use of the Force parameter permanently deleted the list and all of its contents.
The moral of this story – if you need to remove a document from a document library, I would highly recommend you use the Remove-PnPListItem command, rather than Remove-PnPFile.
If for some reason you must use Remove-PnPListItem, you need to be aware that the command will remove whatever it’s told. Take precautions and ensure that the URL you’re using actually points to what you want to be deleted.