2014-06-27 15 views
0

文件夾中有多個文本文件,每個文本文件中有多個受影響的ID。我需要用新的ID替換它們。另外,我想生成一個列出文件名,oldID,newID的文本日誌文件。這個日誌文件是交叉檢查和驗證所必需的。 我有一個csv文件,我從中創建一個數組IdList。我列出了用於替換下面字符串的部分代碼。如何替換文本文件中的多個字符串並同時生成日誌文件?

foreach ($f in gci -r -include "*.txt") 
{ 
Set-Variable -Name filename -value ($f.name) 


for($i=0; $i -le $elementCount; $i++) 
{ 
Write-Host $i 
$oldString= $IdList[$i].OLD_ID+','+$IdList[$i].OLD_ID_TYPE 
$newString= $IdList[$i].NEW_ID+','+$IdList[$i].NEW_ID_TYPE 

gc $f.fullname|ForEach-Object {if($_.contains($oldString)){ "$filename,$oldString,$newString" >> $logFile; $_ -replace $oldString,$newString}}| sc $f.fullname 

} 

} 

我得到錯誤:

Set-Content : The process cannot access the file 'U:\testScript\rapg6785.txt' because it is being used by another process. 
At line:22 char:152 
+  gc $f.fullname|ForEach-Object {if($_.contains($oldString)){ "$filename,$oldString,$newString" >> $logFile; $_ -replace $oldString,$newString}}| sc <<<< $f.fullname 
+ CategoryInfo   : NotSpecified: (:) [Set-Content], IOException 
+ FullyQualifiedErrorId : System.IO.IOException,Microsoft.PowerShell.Commands.SetContentCommand 
+0

嘗試在括號中放入'gc $ f.fullname':'(gc $ f.fullname)' –

+0

謝謝CB。它正在使用(gc $ f.fullname)。你還可以告訴有和沒有括號有什麼不同嗎? – Heman

+0

作爲回答添加;) –

回答

1

嘗試把GC $f.fullname括號:(gc $f.fullname)

通過這種方式,當gc結束時,流水線開始讀取文件並釋放要由另一個進程使用的文件句柄。

相關問題