1
我得到以下异常:删除/清除打开文本文件
该进程无法访问该文件,因为它正被另一个进程使用
我想简单地清除通过PowerShell打开的日志文件。如下所示:
$path = ...
Clear-Content $path -Force
即使文件打开,该如何操作? Windows编辑器和记事本++可以在我的日志查看器打开该文件时执行此操作,但我无法在PowerShell中执行此操作。编辑如何做到这一点?我能用PowerShell以某种方式实现这一点吗?
我也试过Set-Content
清除文件的内容,结果相同。
编辑 - 设置
- 我的程序写入日志文件(没有问题,总是即使日志查看器打开)
- 我用glogg作为日志查看器(http://glogg.bonnefon.org/)
- 如果glogg打开,Powershell脚本失败
- 我可以可靠地重现这一点,并可以看到,Notepad ++和Windows编辑器可以轻松覆盖文件内容并始终(以及我的应用程序仍然可以写当然日志文件),并glogg立即显示新的日志文件的内容
编辑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脚本以下和它的作品完美无瑕:“clear_file的
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
}
内容。蝙蝠“:
break > %1
你不能。 Windows编辑器和记事本++都不能,所以我假设你在某个地方得出了一个错误的结论。如果你对procmon有点熟悉,你可以运行并监视所有文件活动,同时在Powershell/Notepad ++中执行你的操作并从那里得出结论。 –
我做了一个编辑,你可以简单地用任何日志文件重现这一点,并会看到发生这种情况。不知何故编辑器会覆盖该文件,尽管该文件是由日志查看器打开的(无论如何,这是一个查看器,日志文件可以由我的应用程序和编辑器编写,而不是由powershell编写) – prom85
我打开glogg并将其设置为遵循testfile1 。文本。以下在PowerShell中工作没有问题'Clear-Content c:\ temp \ testfile1.txt -Force' –