This tutorial demonstrates how to remove files and directories using PowerShell commands and scripts.

The Remove-Item cmdlet is used to delete files and folders.

PowerShell Commands to Delete Files and Folders

To remove a file from a specified path.

remove-item -Path "c:\\test.txt"

To remove a folder

remove-item -Path "c:\folder"

This command removes files inside the folder. If the folder contains subfolders, the above command might not work.

To remove all subfolders recursively, use the -Recurse option.

remove-item -Path "c:\folder" -Recurse

Additionally, apply -Force to remove files and folders forcefully without confirmation prompt.

Powershell Script to delete files and folder

PowerShell Script to Delete Files and Folders Let’s write a script to delete files and folders.

Create a file named test.ps1 and write the following code/

test.ps1:

$file = "C:\test.txt"
$folder = "C:\mydir"
Remove-Item -Path $file
Remove-Item -Path $folder -Recurse

This script will fail if the file or folder is not present.

To handle this, use an if-else statement to test a conditional expression for file existence.

The conditional expression contains the Test-Path cmdlet, which checks whether a given path exists or not. The path may contain individual files or folders.

Test-Path check given path exists or not, Path might contains indididual files or folders.

if (Test-Path $folder) {
    Remove-Item -Path $folder -Force
    Write-Host "folder  '$folder' Removed"
} else {
    Write-Host "folder '$folder' not exists."
}