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 fileSet-Content -Path "./data.txt" -Value "This is a test file"Write-Host "--------Read content before clear content------"# Reading content from a fileGet-Content -Path "./data.txt"# Clearing content from a fileClear-Content -Path "./data.txt"Write-Host "--------Read content after clear content------"# Reading content from a fileGet-Content -Path "./data.txt"
Explanation
- Line 4: We create a new file,
data.txt, and write content into it using theSet-Contentcmdlet. - Line 8: We display the content in the
data.txtfile using theGet-Contentcmdlet. - Line 11: We clear the content of the
data.txtfile using theClear-Contentcmdlet. - Line 15: We validate if the content is cleared or not by displaying the content in the
data.txtfile.