gpt4 book ai didi

powershell - StreamWriter - 进程无法访问该文件,因为它正被另一个进程使用

转载 作者:行者123 更新时间:2023-12-03 10:01:17 25 4
gpt4 key购买 nike

我正在尝试将 Add-Content 脚本重写为 StreamWriter 版本,原因是该文件约为 140 MB 并且 Add-Content 太慢了。

这是我的 Add-Content 版本,它循环遍历每一行,直到找到以 FILE| 开头的标题行,然后创建一个文件名为该行中的第二个分隔(管道)值。 Add-Content 按预期工作,但速度非常慢。完成它需要 35-40 分钟:

Param(
[string]$filepath = "\\fileserver01\Transfer",
[string]$filename = "sourcedata.txt"
)

$Path = $filepath
$InputFile = (Join-Path $Path $filename)
$Reader = New-Object System.IO.StreamReader($InputFile)

while (($Line = $Reader.ReadLine()) -ne $null) {
if ($Line -match 'FILE\|([^\|]+)') {
$OutputFile = "$($matches[1]).txt"
}
Add-Content (Join-Path $Path $OutputFile) $Line
}

我研究过 StreamWriter 应该更快。这是我的尝试,但我得到了错误

The process cannot access the file '\fileserver01\Transfer\datafile1.txt' because it is being used by another process.

Param(
[string]$filepath = "\\fileserver01\Transfer",
[string]$filename = "sourcedata.txt"
)

$Path = $filepath
$InputFile = (Join-Path $Path $filename)
$Reader = New-Object System.IO.StreamReader($InputFile)

while (($Line = $Reader.ReadLine()) -ne $null) {
if ($Line -match 'FILE\|([^\|]+)') {
$OutputFile = "$($matches[1])"
}
$sw = New-Object System.IO.StreamWriter (Join-Path $Path $OutputFile)
$sw.WriteLine($line)
}

我认为这与在我的循环中使用它有关。

示例数据:

FILE|datafile1|25/04/1725044|0001|37339|10380|TT7525045|0001|37339|10398|TT7525046|0001|78711|15940|TT75FILE|datafile2|25/04/1725047|0001|98745|11263|TT7525048|0001|96960|13011|TT84FILE|datafile3|25/04/1725074|0001|57585|13639|TT8425075|0001|59036|10495|TT84FILE|datafile4|25/04/1725076|0001|75844|13956|TT8425077|0001|17430|01111|TT84

期望的结果是每个 FILE| 标题行 1 个文件,使用第二个分隔值作为文件名。

最佳答案

您正在 while 循环中创建编写器,但从未关闭它,因此您的代码试图在每次迭代时重新打开已打开的输出文件。关闭现有的编写器并在文件名更改时打开一个新的编写器:

while (($Line = $Reader.ReadLine()) -ne $null) {
if ($Line -match 'FILE\|([^\|]+)') {
if ($sw) { $sw.Close(); $sw.Dispose() }
$sw = New-Object IO.StreamWriter (Join-Path $Path $matches[1])
}
$sw.WriteLine($line)
}
if ($sw) { $sw.Close(); $sw.Dispose() }

请注意,这假设您不会打开同一个文件两次。如果同一个输出文件可以在输入文件中多次出现,您需要打开文件进行追加。在那种情况下替换

$sw = New-Object IO.StreamWriter (Join-Path $Path $matches[1])

$sw = [IO.File]::AppendText((Join-Path $Path $matches[1]))

另请注意,代码不执行任何错误处理(例如,输入文件不是以 FILE|... 行开头,输入文件为空等)。您可能想要更改它。

关于powershell - StreamWriter - 进程无法访问该文件,因为它正被另一个进程使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43844386/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com