我遇到了以下异常:
该进程无法访问该文件,因为该文件正由另一个进程
使用
我想简单地清除通过PowerShell打开的日志文件。如下:
$path = ...
Clear-Content $path -Force
即使打开文件,我怎么能这样做? Windows编辑器和 Notepad ++ 可以在我的日志查看器打开文件时执行此操作,但我无法在PowerShell中执行此操作。编辑如何做到这一点?我可以用PowerShell以某种方式实现这一点吗?
我还尝试Set-Content
以相同的结果清除文件内容。
编辑 - 设置
编辑2:ProcMon数据
案例1 - 打开Glogg,powershell失败
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
案例2 - Glogg已关闭且powershell成功
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
编辑3 - 工作替代解决方案
我在我的powershell脚本中调用了以下内容,它完美无瑕:
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
}
“clear_file.bat”的内容:
break > %1
答案 0 :(得分:1)
最后我找到了一个有效的解决方案:
而不是
"" | Out-File $path -NoNewline -Encoding ASCII
可以使用
Clear-Content
<强>为什么强>
似乎Out-File
正在创建一个新文件并用它替换旧文件,而from pyparsing import *
尝试写入现有文件(因此打开的读取句柄不会影响这个)