3

特定のディレクトリ構造内のすべてのファイルのコンテンツを置き換えようとしています。

get-childItem temp\*.* -recurse |
    get-content |
    foreach-object {$_.replace($stringToFind1, $stringToPlace1)} |
    set-content [original filename]

元のget-childItemからファイル名を取得して、set-contentで使用できますか?

4

2 に答える 2

8

各ファイルの処理を追加します。

get-childItem *.* -recurse | % `
{
    $filepath = $_.FullName;
    (get-content $filepath) |
        % { $_ -replace $stringToFind1, $stringToPlace1 } |
        set-content $filepath -Force
}

キーポイント:

  1. $filepath = $_.FullName;—ファイルへのパスを取得
  2. (get-content $filepath)—コンテンツを取得してファイルを閉じる
  3. set-content $filepath -Force—変更されたコンテンツを保存します
于 2012-08-03T11:08:32.657 に答える
5

単純に使用できますが、各ファイル$_の周りにも必要です。foreach-object@akimの答えは機能しますが、の使用$filepathは不要です。

gci temp\*.*  -recurse | foreach-object { (Get-Content $_) | ForEach-Object { $_ -replace $stringToFind1, $stringToPlace1 } | Set-Content $_ }
于 2012-08-03T12:00:14.570 に答える