3

この問題が発生し、すべてのテキストファイルの文字列「121212」をその親フォルダの名前に置き換える必要があります(たとえば、親フォルダの名前が「123456」の場合、文字列「121212」を「123456」に置き換える必要があります)。

次のコマンドでこれを行う方法を理解したと思いました。

PS E:\testenvironment> $parent=get-childitem -recurse | where {$_.FullName -match "[testenvironment]\\\d{6}$"} | foreach {$_.Name}
PS E:\testenvironment> $parent
123456
456789
654321
987654
PS E:\testenvironment> $files=get-childitem -recurse | where {$_.FullName -match "\\\d{6,6}\\AS400\\test3.txt$"} | foreach {$_.FullName}
PS E:\testenvironment> $files
E:\testenvironment\123456\AS400\test3.txt
E:\testenvironment\456789\as400\test3.txt
E:\testenvironment\654321\AS400\test3.txt
E:\testenvironment\987654\AS400\test3.txt
PS E:\testenvironment> foreach ($file in ($files)) {Get-Content "$file" | foreach-Object {$_ -replace "121212", "($name in ($parent))"} | set-content "$file"}

しかし、私はこのメッセージを受け取ります:

Set-Content : The process cannot access the file 'E:\testenvironment\123456\AS400\test3.txt' **because it is being used by another process**.
At line:1 char:127
+ foreach ($file in ($files)) {Get-Content "$file" | foreach-Object {$_ -replace "121212", "($name in ($parent))"} | set-content <<<<  "$file"}
    + CategoryInfo          : NotSpecified: (:) [Set-Content], IOException
    + FullyQualifiedErrorId : System.IO.IOException,Microsoft.PowerShell.Commands.SetContentCommand

(...もちろんすべてのtest3.txtファイルに対してこれを受け取ります...)

「現在のメモリ」を新しい変数に入れて、ファイル(現在メモリ内にある)を新しいデータで上書きできるようにする方法がわかりません。

4

1 に答える 1

0

すべてのテキストファイルが投稿したディレクトリ構造にある場合、次のように作業が完了します。

get-childitem $testEnvPath -recurse -filter "*.txt" | foreach{
    $content = Get-Content $_.fullname 
    #To get the file's grandparent directory name ($_.fullname -split '\\')[-3]
    $content -replace "121212", ($_.fullname -split '\\')[-3] | 
    set-content $_.fullname
}

メモリ内の次のファイル/ディレクトリに「移動」するには、これらの項目の列挙はforeachステートメントの内部にある必要がありますが、外部で列挙している必要があります。

お役に立てば幸いです。

于 2012-12-08T19:18:57.457 に答える