如何替换文本文件中的多个字符串并同时生成日志文件?

时间:2014-06-27 09:02:56

标签: powershell

文件夹中有多个文本文件,每个文本文件中有多个受影响的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

1 个答案:

答案 0 :(得分:1)

尝试将gc $f.fullname放入括号:(gc $f.fullname)

通过这种方式,管道在gc结束时启动以读取文件并释放文件句柄以供另一个进程使用。

相关问题