我有一个条件会启动PowerShell脚本,以将短字符串附加到文本文件。这种情况会迅速触发,因此同一脚本将文件多次写入。此外,将从该文本文件中批量导入一个单独的脚本(不那么频繁)。
每当这种情况很快发生时,我都会收到错误消息:“该进程无法访问文件'file_name',因为它正在被另一个进程使用。” 当我在Python(我的主要语言)中执行相同的追加操作时,我没有得到相同的错误,但是我可以使用一些帮助在PowerShell中修复此错误。
$action = $args[0]
$output_filename = $args[1]
$item = $args[2]
if ($action -eq 'direct'){
$file_path = $output_filename
$sw = New-Object -typename System.IO.StreamWriter($file_path, "true")
$sw.WriteLine($item)
$sw.Close() }
我还尝试了以下方法而不是StreamWriter,但显然,添加内容和输出文件的性能很弱(http://sqlblog.com/blogs/linchi_shea/archive/2010/01/04/add-content-and -out-file-not-for-performance.aspx):
out-file -Append -FilePath $file_path -InputObject $item }
可以尝试这样的事情:
while ($true)
{
Try {
[IO.File]::OpenWrite($file_path).close()
Add-Content -FilePath $file_path -InputObject $item
Break
}
Catch {}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句