Boris Callens
Boris Callens

Reputation: 93357

Read all files, change content, save again

I'm trying to do a replace in content of all files in a certain directory structure.

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

Can I get the filename from the original get-childItem to use it in the set-content?

Upvotes: 3

Views: 7052

Answers (2)

Dan Puzey
Dan Puzey

Reputation: 34218

You can simply use $_, but you need a foreach-object around each file, too. While @akim's answer will work, the use of $filepath is unnecessary:

gci temp\*.*  -recurse | foreach-object { (Get-Content $_) | ForEach-Object { $_ -replace $stringToFind1, $stringToPlace1 } | Set-Content $_ }

Upvotes: 5

Akim
Akim

Reputation: 8679

Add processing for each file:

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

Key points:

  1. $filepath = $_.FullName; — get path to file
  2. (get-content $filepath) — get content and close file
  3. set-content $filepath -Force — save modified content

Upvotes: 8

Related Questions