PowerShell has Remove-Item cmdlet used to delete one or more items. These items can be files, folders, variables, registry keys, functions, and aliases. Using PowerShell Remove-Item cmdlet, we can check if folder exists and then delete the folder.
In this article, I will explain how to use PowerShell Remove-Item to delete folder if exists.
PowerShell Delete Folder If Exists
PowerShell Remove-Item cmdlet delete folder using specified folder path, run below PowerShell script
$FolderName = "D:\Logs-FTP01\" if (Test-Path $FolderName) { Write-Host "Folder Exists" Remove-Item $FolderName -Force } else { Write-Host "Folder Doesn't Exists" }
In the above PowerShell script, the $FolderName variable contains a directory path.
PowerShell Test-Path
cmdlet check if folder exists or not. If folder exists, it will return $True
and $False
if the folder doesn’t exist on a specified path.
PowerShell Remove-Item is used to delete folder if exists on the specified path given by the $FolderName variable. Using -Force parameter to forcefully delete folder or delete file if exists which have read-only permission.
Above PowerShell script, remove Logs-FTP01 folder as it exists on the specified directory.
Note: If you try to use a script to delete excel or CSV file while the file is opened, it will throw an error as “The process cannot access the file, because it is being used by another process.”
Cool Tip: how to count files in the folder using Get-ChildItem in PowerShell!
PowerShell Script to Delete Folder and Subfolder
PowerShell Remove-Item cmdlet used to delete folder if exists using folder name path specified.
The folder may contain files and subfolders. Use below PowerShell script to delete folder and subfolder as below
$FolderName = "D:\Logs-FTP03\" if (Test-Path $FolderName) { Write-Host "Folder Exists" Remove-Item $FolderName -Recurse -Force } else { Write-Host "Folder Doesn't Exists" }
In the above PowerShell script, Remove-Item cmdlet recursively delete files and folder if exists in the specified folder and using -Force parameter to forcefully delete folder and delete file if exists.
Cool Tip: Find Large size files in PowerShell!
Conclusion
I hope the above article on how to delete folder if exists in PowerShell using the Remove-Item cmdlet is helpful to you.
Using Recurse parameter to recursively delete folder and subfolders in PowerShell.
To delete a read-only file or access permission denied file, use the Force parameter to forcefully remove file from the specified location.
You can read more about how to use PowerShell mkdir and PowerShell New-Item to create directory in PowerShell.
You can find more topics about PowerShell Active Directory commands and PowerShell basics on the ShellGeek home page.