While working on files based operation, often we may need to clear content of file or delete content of all files like log files in the specified directory. PowerShell management module provides Clear-Content cmdlet to clear content of file.
Clear-Content cmdlet in PowerShell delete content of the file without deleting the file. It deletes the text from the file, file still exists but is empty.
In this article, I will explain how to use
Clear-Content in PowerShell to remove content from text file, clear content of all files in a specified directory.
Clear-Content cmdlet delete the content of file. As a result, the file exists but the file is empty.
Clear-Content [-Path] <String> [-Filter <String>] [-Include <String>] [-Exclude <String>] [-Force] [-Credential <PSCredential>] [-WhatIf] [-Confirm] [-Stream <String>] [<CommonParameters>]
Clear-Content of File
To delete the content of file in the specified directory, use
Clear-Content cmdlet in PowerShell as below
Clear-Content -Path .\PowerShell-File.txt
In the above clear content example, Clear-Content cmdlet delete the content of the text file specified by the Path parameter.
Delete Content of all files
You can use Clear-Content cmdlet in PowerShell to delete content of all txt files in the given directory and subdirectories specified by a wildcard character.
In the above PowerShell clear content example,
Clear-Content remove the content from a text file from directory and subdirectories using the specified wildcard character ( *)
Clear Content of read only file
You can use Clear-Content cmdlet in PowerShell to remove content from read only text file with Force parameter.
If the file is readonly and if you try to use Clear-Content to remove content from text file, it will throw exception as below
PS D:\PowerShell> Clear-Content -Path .\DestinationFile.txt Clear-Content : Access to the path 'D:\PowerShell\DestinationFile.txt' is denied. At line:1 char:1 + Clear-Content -Path .\DestinationFile.txt + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : PermissionDenied: (D:\PowerShell\DestinationFile.txt:String) [Clear-Content], Unauthoriz edAccessException + FullyQualifiedErrorId : ClearContentUnauthorizedAccessError,Microsoft.PowerShell.Commands.ClearContentCommand
It throws an error as Clear-Content access to the path is denied, ClearContentUnauthorizedAccessError.
To avoid unauthorizedAccessError while deleting the text from file, use the Force parameter as below
Clear-Content -Path .\DestinationFile.txt -Force
In the above PowerShell example, Clear-Content cmdlet clear content of read only text file specified by Path and Force parameters.
I hope above article on Clear-Content cmdlet in PowerShell help you to remove content from text file, delete all files content in directory and subdirectories using a wildcard character.
You can find more topics about PowerShell Active Directory commands and PowerShell basics on ShellGeek home page.