[PowerShell] How to clear contents of a file

Clear Contents of a File

Temporary files can take up considerable space in a database and eventually slow down computers. Administrators can use the following PowerShell script to completely clear the contents of files remotely. If you want to delete the entire text file content using PowerShell, then we can use the Clear-Content command. 

How to use clear-content in PowerShell to empty a single file

Execute the script to clear the complete contents of a file by providing the file path as a parameter. In the below example, the TXT file stored at C:\Users will be cleared. You can also directly use the Clear-Content command for the TXT file or other files to clear the entire content of the file.

Script

<#
.SYNOPSIS
This script can be used to clear contents of a file.
.DESCRIPTION
This script can be used to clear contents of a file.
.EXAMPLE
C:\PS> C:\Script\Clear_File.ps1 C:\Users\gautam-2374\Desktop test.txt
Clears the contents of the file.
#>

param([String] $path)
“File Content”
#Gets the content of a file.

Get-Content $path
#Clears the content of a file.

Clear-Content $path
“File Content Cleared!”
Get-Content $path

 

 



    • Related Articles

    • Delete all temp folders contents

      The unfortunate side effect of using Windows as a client operating system is that temporary folders can accumulate over time and take up considerable space in the database or hard drives and end up slowing the computer considerably. However, deleting ...
    • Remove read only property of a file

      A common issue that administrators face while restoring files from their backups is that the read-only property of the files comes marked by default. This can cause serious trouble as end users will not be able to edit their documents without ...
    • Create a ShortCut for an Exe File

      Creating a shortcut to an application on multiple end user desktops can be a laborious task. However, the process is pretty straightforward when using a PowerShell script. In the following script, provide the path of the EXE file and the exact path ...
    • Powershell Script to Find and Replace Text in a File

      To find and replace a particular word throughout a file on multiple computers is as laborious as one can imagine. However, with the help of the following PowerShell script, one can easily find a particular word and replace it with a word of choice.   ...
    • Convert a File to a desired naming Format (ASCII, Unicode or UTF8)

      Administrators dealing with a huge number of files know from experience that certain files from applications are not retrieved in a naming format that is compatible with the rest of their workflow. When these files are in the thousands, converting ...