What is the Clear-Content cmdlet in PowerShell?

Overview

We can use the Clear-Content cmdlet in PowerShell to clear the contents of a file. This cmdlet does not delete the file, but only clears the content present in it.

Syntax

Clear-Content -Path "path to file"

Parameters

The function takes the following mandatory parameter:

  • Path: This is the path we provide to the file.

Return value

This cmdlet does not return anything.

Let's take a look at an example of this.

Example

In the following example, we create a data.txt file and insert some content into it. We will clear it using the Clean-Content cmdlet.

#!/usr/bin/pwsh -Command
# Writing content to a file
Set-Content -Path "./data.txt" -Value "This is a test file"
Write-Host "--------Read content before clear content------"
# Reading content from a file
Get-Content -Path "./data.txt"
# Clearing content from a file
Clear-Content -Path "./data.txt"
Write-Host "--------Read content after clear content------"
# Reading content from a file
Get-Content -Path "./data.txt"

Explanation

  • Line 4: We create a new file, data.txt, and write content into it using the Set-Content cmdlet.
  • Line 8: We display the content in the data.txt file using the Get-Content cmdlet.
  • Line 11: We clear the content of the data.txt file using the Clear-Content cmdlet.
  • Line 15: We validate if the content is cleared or not by displaying the content in the data.txt file.

Free Resources