我正在嘗試將Add-Content
腳本重寫爲StreamWriter
版本,原因是該文件大約140 MB和Add-Content
太慢了。StreamWriter - 進程無法訪問文件,因爲它正在被另一個進程使用
這是我的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
應該會更快。這是我的嘗試,但我得到錯誤
進程無法訪問文件'\ fileserver01 \ Transfer \ datafile1.txt',因爲它正在被另一個進程使用。
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/17 25044|0001|37339|10380|TT75 25045|0001|37339|10398|TT75 25046|0001|78711|15940|TT75 FILE|datafile2|25/04/17 25047|0001|98745|11263|TT75 25048|0001|96960|13011|TT84 FILE|datafile3|25/04/17 25074|0001|57585|13639|TT84 25075|0001|59036|10495|TT84 FILE|datafile4|25/04/17 25076|0001|75844|13956|TT84 25077|0001|17430|01111|TT84
期望的結果是使用所述第二分隔值作爲文件名每FILE|
1文件heade行。
嗨,不應該'*在* while循環之前,而不是*內部*它是?*之前*不是新的對象System.IO.StreamWriter(加入路徑$路徑$ OutputFile)? – sodawillow