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.
Clear-Content -Path "path to file"
The function takes the following mandatory parameter:
Path
: This is the path we provide to the file.This cmdlet does not return anything.
Let's take a look at an example of this.
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"
data.txt
, and write content into it using the Set-Content
cmdlet.data.txt
file using the Get-Content
cmdlet.data.txt
file using the Clear-Content
cmdlet.data.txt
file.