多个PowerShell脚本写入相同的文件

时间:2014-06-02 17:04:56

标签: powershell

我有条件启动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 }

1 个答案:

答案 0 :(得分:1)

可以尝试这样的事情:

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

    Catch {}
 }
相关问题