How to delete all the file contents using PowerShell?


If you want to delete the entire text file content using PowerShell, then we can use the Clear-Content command. For example, we have the below text file called Locations.txt on the C:\Temp path. You can check the content using the below file.

Get-Content C:\temp\locations.txt

To clear the file content, we can use the below command.

Clear-Content C:\Temp\locations.txt -Force

-Force switch is used to clear the contents without user confirmation.

When you use this command with the pipeline in the Get-Content command, it will generate an IO Exception error that the file is in use because we are already retrieving the contents using Get-Content and then trying to delete the existing content.

Clear-Content : The process cannot access the file 'C:\Temp\locations.txt' because it is being used by another process.
At line:1 char:37
+ Get-Content C:\Temp\locations.txt | Clear-Content
+ ~~~~~~~~~~~~~
+ CategoryInfo : WriteError: (C:\Temp\locations.txt:String) [Clear-Content], IOException
+ FullyQualifiedErrorId : ClearContentIOError,Microsoft.PowerShell.Commands.ClearContentCommand

To clear the file contents for the CSV, we can first import that CSV file and then use the Clear() method to clear the file content. For example,

Example

PS C:\> $csvfile = Import-Csv C:\Temp\Services.csv
PS C:\> $csvfile.Clear()

In the above example, the CSV file stored at C:\temp will be cleared. You can also directly use the Clear-Content command for the CSV file or other files to clear the entire content of the file.

Updated on: 08-Feb-2021

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements