Tech News Today
  • Hardware
    • Motherboards
    • CPUs
    • Graphic Cards
    • RAM
    • SSDs
    • Computer Cases
    • Monitors
    • Peripherals
    • Power Supply Unit
    • PC Builds
    • Computer Tips
  • Software
  • Operating System
    • Windows
    • Mac
    • Linux
  • Gaming
  • Mobile
  • Console
  • More
    • Internet
    • Networking
    • Security
    • Buyer’s Guide
    • Gadgets
    • Laptops
    • Reviews
    • How To
    • News
Facebook Twitter Instagram
Tech News Today
  • Hardware
    • Motherboards
    • CPUs
    • Graphic Cards
    • RAM
    • SSDs
    • Computer Cases
    • Monitors
    • Peripherals
    • Power Supply Unit
    • PC Builds
    • Computer Tips
  • Software
  • Operating System
    • Windows
    • Mac
    • Linux
  • Gaming
  • Mobile
  • Console
  • More
    • Internet
    • Networking
    • Security
    • Buyer’s Guide
    • Gadgets
    • Laptops
    • Reviews
    • How To
    • News
Tech News Today
Home»Windows»How to Check and Delete Existing File in Powershell

How to Check and Delete Existing File in Powershell

Bhishu AcharyaBy Bhishu AcharyaOctober 20, 2022
powershell check if file exists

If you’re trying to delete a particular item regardless of the file type, you’ll have to first check whether it exists or not. Else, you’re likely going to encounter an unexpected error.

Although checking and removing files is relatively easy using the Windows GUI, you still have to navigate to multiple windows just to delete a single file. On the other hand, Powershell lets you do the same task using simple and short commands.

Well, you can simply use the Remove-Item cmdlet to delete a specific file from the given path. However, there are multiple commands and a plethora of methods to check whether the item you’re trying to delete exists or not.

Regarding the same, this article will guide you with the various commands and useful techniques to check and delete the existing files in Windows Powershell.

Table of Contents

  • How to Check and Delete an Existing File in Powershell?
    • Using Test-Path
    • Using Get-Item
    • Using [System.IO.File]::Exists
  • How to Delete Multiple Existing Files in Powershell?
    • All Files From a Specific Folder
    • Hidden or Read-Only Files
    • All Files of the Same Type

How to Check and Delete an Existing File in Powershell?

Windows Powershell is a terminal that lets users automate tasks using scripting languages. Thus, creating, reading, updating, or deleting files using this utility is easy to understand and implement.

Probably, you have tried checking if a file exists in Bash, Command Prompt, and Windows GUI. Now, in this section, you will learn different commands to do it in Powershell and delete it if required.

Using Test-Path

Test-Path is a command that determines whether the provided path/address exists. Basically, running this cmdlet on Powershell outputs a boolean expression. Here, True indicates that the file you’re trying to access exists, and False means it doesn’t. Below is the syntax for Test-Path:
Test-Path <Path>

For example, to check whether the file “text.txt” exists inside the Documents directory and delete it, here’s what you can do:

  1. In the Powershell Window, copy and paste the below command:
    Test-Path Documents\text.txt
  2. Now, hit enter, and you should get the value ‘True’ if it exists.
    test path true
    Else, you’ll get the value ‘False’ like below.
    test path false
  3. If it exists, you can now use the below command to delete the file:
    Remove-Item Documents\text.txt
    test path remove item success
    However, if you try deleting the file that doesn’t exist, you’ll receive an error message like the one below.
    test path remove item error

If you do not prefer the boolean expressions, you can use the if and else statements to generate actual messages. Also, writing this simple code will help you delete the existing file without having to run multiple commands:

$MyFile = "Documents\text.txt"
if (Test-Path $MyFile) {
Remove-Item $MyFile
Write-Host "The file was found and has been deleted successfully."
}
else
{
Write-Host "The file you're searching for doesn't exist."
}

In the above code, we are basically representing the location by the variable MyFile. Now, the if (Test-Path $MyFile) determines whether the path exists or not. 

If it does, you’ll encounter the message “The file was found and has been deleted successfully.” and the Remove-Item $MyFile command deletes your file.
test path exists and deleted
To ensure this, you can use the Test-Path Documents\text.txt again, and you should get the False output.

However, if the file doesn’t exist, you’ll simply encounter the “The file you’re searching for doesn’t exist.” message instead of the Cannot find path error as earlier.
test path doesn't exist

Using Get-Item

Using Get-Item is as simple as using the Test-Path. However, this cmdlet doesn’t determine if a file exists using boolean expressions. Instead, it outputs your file’s mode, last write time, length, and name, along with its type. Given below is the syntax of Get-Item:
Get-Item <Path>

Please follow the instructions below to learn how to identify and delete an existing file using the Get-Item cmdlet. For demonstration purposes, we will remove an image file “image.bmp” from the Documents directory:

  1. After launching Powershell, paste the below command:
    Get-Item Documents\image.bmp
  2. Hit Enter, and you’ll get the file’s details if the file exists.
    get item
    Otherwise, you’ll encounter the Cannot find path error.
    get item cannot find path
  3. If the file exists, now use the below command to remove it from the directory:
    Remove-Item Documents\image.bmp
    get item remove item success
    But if the file doesn’t exist and you try deleting it, you’ll encounter the Cannot find path error again.
    remove item cannot find path

Well, you can also use the below program to check and delete an existing file in Powershell using the Get-Item:

$MyFile = "Documents\image.bmp"
if(Get-Item $MyFile -ErrorAction Ignore)
{
Remove-Item $MyFile
Write-Host "The file was found and has been deleted successfully."
}
else
{
Write-Host "The file you're searching for doesn't exist and can’t be deleted."
}

In the above script, we have first assigned a variable MyFile that stores the path of the image.bmp file. Then, we set the if condition as Get-Item $MyFile -ErrorAction Ignore, where Get-Item $MyFile gets the item from the location, and –ErrorAction Ignore will discard the error if the file doesn’t exist.

Basically, if your file exists, you’ll get the “The file was found and has been deleted successfully” message, and the item is deleted.
get item exists and deleted
Otherwise, you’ll encounter “The file you’re searching for doesn’t exist and can’t be deleted.”
get item doesn't exist

Note: You can also use the Get-ChildItem cmdlet instead of Get-Item. Both commands work exactly the same.

Using [System.IO.File]::Exists

System.IO deals with reading and writing into the files in the .NET framework class library. Using the namespace, we can quickly determine if a file exists. Then, using the Remove-Item cmdlet, deletion is also possible. 

Like Test-Path, the [System.IO.File]::Exists command also throws a boolean expression to determine whether a file exists or not. Here’s the syntax of the [System.IO.File]::Exists cmdlet:
[System.IO.File]::Exists(“<Path>”)

For demonstration, let’s check if an MS Word file ‘word.docx’ exists in the Document directory and delete this item:

  1. Run the below cmdlet on the Powershell window:
    [System.IO.File]::Exists("Documents\word.docx")
  2. Now, Powershell returns True if the file exists.
    system io file exists true
    Otherwise, the output is False.
    system io file exists false
  3. If the file you’re searching for exists, use the following command to delete it:
    Remove-Item Documents\word.docx
    system io file exists remove item success
    Well, Powershell triggers the Cannot find path error if you try deleting a nonexistent file.
    system io file exists remove item path doesn't exist

Furthermore, you can try the below program that adopts the [System.IO.File]::Exists cmdlet to delete an existing file on Windows Powershell:

$MyFile = "Documents\word.docx"
if([System.IO.File]::Exists($MyFile))
{
Remove-Item $MyFile
Write-Host "The file was found and has been deleted successfully"
}
else
{
Write-Host "The file you're searching for doesn't exist and can’t be deleted."
}

In the above program, MyFile is a variable that stores the path of the MS Word file. Now, using the [System.IO.File]::Exists($MyFile), we get to know whether the item exists or not.

Now, instead of displaying the boolean expression, the Write-Host cmdlet displays “The file was found and has been deleted successfully.” and deletes the file if it exists.
system io file exists deletion success
Similarly, you get the message, “The file you’re searching for doesn’t exist and can’t be deleted.” if the path isn’t set right.
system io file exists can't be deleted

How to Delete Multiple Existing Files in Powershell?

Sometimes, you might want to delete multiple files from a folder or directory. In such a case, Windows Powershell provides a feature to remove all or selected files permanently. 

Caution: The items won’t move to the recycle bin. Basically, the action is equivalent to performing permanent delete using the Shift + Delete keys on the Windows interface.

In this section, we will discuss some easy and effective ways to check and delete multiple existing files in the Powershell program.

All Files From a Specific Folder

If you wish to delete all the files from a particular folder regardless of the file type or extension, here’s the appropriate command you can use:
Remove-Item <Path>\*.*

For example, let’s check the files inside the Example folder and delete all the files inside it. Here’s how you can do it:

  1. Firstly, use the below command to check the files inside the Example folder:
    Get-ChildItem C:\Users\Bhishu\Desktop\Example
    check multiple files using get-childitem
  2. Now, you can run the below code to delete all these files:
    Remove-Item C:\Users\Bhishu\Desktop\Example\*.*
    remove all items
  3. To confirm that all your files are removed, use the Get-ChildItem cmdlet again, which shouldn’t display anything.
    get child item doesn't display anything

Hidden or Read-Only Files

Well, removing all the files won’t delete those with read-only and hidden attributes. In fact, if you try removing such items, you’ll get the You do not have sufficient access rights to perform this operation error.
you do not have sufficient access rights to perform this operation
Hence, you need to use the -Force parameter to delete them forcefully:
Remove-Item <Path> -Force

Let’s take an example to understand this. Suppose we have a hidden and read-only file, ‘word.docx’, inside the Example folder. So, to remove this, here’s the correct command you need to use:
Remove-Item C:\Users\Bhishu\Desktop\Example\word.docx -Force
delete hidden and read only files using force parameter

Now, you should not get the error. In fact, you can validate this by using the Test-Path command to check whether the hidden file now exists in the same location.

All Files of the Same Type

If you do not want to delete all the files from a specific folder but rather wish to remove only those items having the same file type, here’s the syntax you’re looking for:
Remove-Item <Path>*[file-type]

For example, to delete all the files having the .docx extension from the Example folder, please follow the below steps:

  1. First of all, run the below script to check what files exist in the folder:
    Get-Item C:\Users\bishu\Desktop\Example\*.*
    check items of different file types
    Here, the *.* will show all the files regardless of their extension.
  2. Since you’re only trying to remove files having the same type, use the following command that should do the job:
    Remove-Item C:\Users\bishu\Desktop\Example\*.docx
    Basically, the *.docx will help delete all those files with the .docx extension. Similarly, you can replace it with any file type (.bmp, .txt, .jpeg), which will delete only those files with the corresponding extension.
  3. Finally, you can use the Get-Item command again to view all the files in the Example folder. Indeed, you’ll notice that all the .docx files get removed.
    items of same file type are deleted
how-to
Bhishu Acharya
  • Tumblr
  • LinkedIn

Bhishu Acharya is a technical content writer at TechNewsToday. He specializes in monitors, laptops, storage devices, and other peripherals. Apart from computer hardware, you can also find his how-to and troubleshooting articles on Windows, internet, security, and networking. Ever since getting his hands on a personal computer, Bhishu started exploring its internal components at just 10. His growing curiosity led him to undertake the Computer Science & Information Technology degree and is just a year away from graduation. While balancing his study and work life for over four years, he has harnessed different sets of technical skills. With his expertise, he is now dedicated to helping netizens looking for hardware and software-related fixes. Today, Bhishu’s proficiency extends beyond computer hardware. In his spare time, he enjoys coding and learning new programming languages. You can contact him at bhishu@technewstoday.com

Related Posts

Power on Self test

What is Power on Self Test (POST)? How Does It Work

February 6, 2023
how to make cursor bigger

How to Make Cursor Bigger

February 3, 2023
enable secure boot msi bios

How to Enable Secure Boot on MSI Motherboard

February 3, 2023
how to add device to microsoft account

How to Add Device to Microsoft Account

February 2, 2023
how to delete win backup files

How to Delete Backup Files on Windows

January 29, 2023
how to reset password on hp laptop

How to Reset Password on HP Laptop

January 30, 2023
Add A Comment

Leave A Reply Cancel Reply

Latest Posts
Power on Self test

What is Power on Self Test (POST)? How Does It Work

February 6, 2023
usb a vs usb c

USB A Vs USB C – What’s the Difference?

January 31, 2023
how long does a cmos battery last

How Long Does a CMOS Battery Last

January 25, 2023
You may also like
find cursor windows

How to Quickly Find Cursor in Windows

February 6, 2023
Surface Mouse Not Working

Surface Mouse Not Working? Try These Fixes

February 6, 2023
how-to-change-ink-in-hp-printer

How to Change Ink in HP Printer? Step-by-Step Guide

February 6, 2023
Recommended
Cookie Clicker Garden Guide

Cookie Clicker Garden Guide to Unlocking Every Seed

September 26, 2021
monitor no signal

Computer Turns On But Monitor Says No Signal (9 Ways To Fix)

November 10, 2022
Facebook Twitter Pinterest
  • Home
  • About Us
  • Our Team
  • Editorial Guidelines
  • Privacy Policy
  • Affiliate Disclosure
© 2023 TechNewsToday.

Type above and press Enter to search. Press Esc to cancel.