Reputation: 17838
I'm getting following exception:
The process cannot access the file because it is being used by another process
I want to simply clear a log file that is opened via PowerShell. Like following:
$path = ...
Clear-Content $path -Force
How can I do this even if the file is opened? Windows Editor and Notepad++ can do it while the file is opened by my log viewer, but I can't do it in PowerShell. How do the editors do this? Can I somehow achieve this with PowerShell as well?
I also tried Set-Content
to clear the content of the file with the same result.
EDIT - Setup
EDIT 2: ProcMon data
Case 1 - Glogg is opened and powershell fails
11:11:12,1441593 powershell.exe 10304 QueryOpen D:\VW_LOG.txt SUCCESS CreationTime: 16.10.2014 09:59:18, LastAccessTime: 16.10.2014 10:13:51, LastWriteTime: 13.10.2017 10:22:07, ChangeTime: 13.10.2017 10:22:07, AllocationSize: 28.672, EndOfFile: 26.451, FileAttributes: A
11:11:12,1442828 powershell.exe 10304 CreateFile D:\VW_LOG.txt SHARING VIOLATION Desired Access: Generic Write, Read Attributes, Disposition: Open, Options: Synchronous IO Non-Alert, Non-Directory File, Open No Recall, Attributes: n/a, ShareMode: Write, AllocationSize: n/a
Case 2 - Glogg is closed and powershell succeeds
11:12:48,9053637 powershell.exe 10304 QueryOpen D:\VW_LOG.txt SUCCESS CreationTime: 16.10.2014 09:59:18, LastAccessTime: 16.10.2014 10:13:51, LastWriteTime: 13.10.2017 10:22:07, ChangeTime: 13.10.2017 10:22:07, AllocationSize: 28.672, EndOfFile: 26.451, FileAttributes: A
11:12:48,9055053 powershell.exe 10304 CreateFile D:\VW_LOG.txt SUCCESS Desired Access: Generic Write, Read Attributes, Disposition: Open, Options: Synchronous IO Non-Alert, Non-Directory File, Open No Recall, Attributes: n/a, ShareMode: Write, AllocationSize: n/a, OpenResult: Opened
11:12:48,9055581 powershell.exe 10304 QuerySecurityFile D:\VW_LOG.txt SUCCESS Information: Attribute
11:12:48,9055808 powershell.exe 10304 SetAllocationInformationFile D:\VW_LOG.txt SUCCESS AllocationSize: 0
11:12:48,9058881 powershell.exe 10304 CloseFile D:\VW_LOG.txt SUCCESS
EDIT 3 - working alternative solution
I call following in my powershell script and it works flawless:
ExecuteSimpleBatch "clear_file.bat" $path
function ExecuteSimpleBatch($file, $par)
{
$fileName = Split-Path $file -leaf
$fileFolder = Split-Path $file -parent
Start-Process "cmd" -ArgumentList '/c', $file, $par -WorkingDirectory $fileFolder -WindowStyle hidden
}
Content of "clear_file.bat":
break > %1
Upvotes: 2
Views: 3099
Reputation: 17838
Finally I found a working solution:
Instead of
Clear-Content $path
it's possible to use
"" | Out-File $path -NoNewline -Encoding ASCII
Why
Seems like Clear-Content
is creating a new file and replaces the old one with it, while Out-File
tries to write into an existing file (so opened read handles do not effect this)
Upvotes: 2