【问题标题】:Multiple PowerShell Scripts Writing to Same File多个 PowerShell 脚本写入同一文件
【发布时间】:2014-06-02 17:04:56
【问题描述】:

我有一个启动 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,但显然 Add-Content 和 Out-File (http://sqlblog.com/blogs/linchi_shea/archive/2010/01/04/add-content-and-out-file-are-not-for-performance.aspx) 的性能很弱:

out-file -Append -FilePath $file_path -InputObject $item }

【问题讨论】:

    标签: powershell


    【解决方案1】:

    可能会尝试这样的事情:

    while ($true)
    {
      Try {
            [IO.File]::OpenWrite($file_path).close()
            Add-Content -FilePath $file_path -InputObject $item
            Break
          }
    
        Catch {}
     }
    

    【讨论】:

    • 谢谢,我使用了 Try/Catch with a Break 作为解决方案。不过,我应该注意,我仍然使用 StreamWriter,因为据说它要快得多。
    猜你喜欢
    • 1970-01-01
    • 2012-06-24
    • 1970-01-01
    • 2013-01-26
    • 2020-12-10
    • 2021-03-23
    • 2022-12-12
    • 2020-04-04
    • 1970-01-01
    相关资源
    最近更新 更多