Need to clear the contents of a log file(s) which is(are) locked by a process already from command prompt. When I tried doing
echo "" > filename
I get a error saying, the file is locked by a process.
I couldn't even open the file in notepad, clear contents and save.
Currently I'm opening the file in notepad++ and quickly pressing CTRL + a,CTRL+x,CTRL+s :)
Is there a way to get this done from cmd? How is notepad++ able to handle edit and save while notepad is not able to?
3 Answers
You could use a program like Unlocker to release the lock:
I found the best solution for me is Powershell> Clear-Content filename.log
1The
Clear-Contentcmdlet enables you to erase the contents of a file without deleting the file itself. For example, suppose you run this command:
Clear-Content c:\scripts\test.txtWhen you execute that command the file Test.txt will still be in the folder C:\Scripts; there just won’t be any data of any kind in the file.
Wildcard characters can be used with Clear-Content. This command erases the contents of any file in C:\Scripts whose file name starts with the letter E:
Clear-Content c:\scripts\e*You are not limited to erasing only text files. The following command deletes all the data in an Excel spreadsheet:
Clear-Content c:\scripts\test.xlsAnd this command erases the contents of the Word document C:\Scripts\Test.doc:
Clear-Content c:\scripts\test.doc
Locked files cannot be deleted, but they can be renamed. It could be that Notepad++ is using "safe saves" – creating a temporary file with the new contents, then quickly deleting the original (this step probably fails) and renaming temporary file to the original name.