Reputation: 93357
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
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
Reputation: 8679
Add processing for each file:
get-childItem *.* -recurse | % `
{
$filepath = $_.FullName;
(get-content $filepath) |
% { $_ -replace $stringToFind1, $stringToPlace1 } |
set-content $filepath -Force
}
Key points:
$filepath = $_.FullName;
— get path to file(get-content $filepath)
— get content and close fileset-content $filepath -Force
— save modified contentUpvotes: 8