我正在尝试替换某个目录结构中所有文件的内容。
get-childItem temp\*.* -recurse |
get-content |
foreach-object {$_.replace($stringToFind1, $stringToPlace1)} |
set-content [original filename]
我可以从原始 get-childItem 获取文件名以在 set-content 中使用它吗?
我正在尝试替换某个目录结构中所有文件的内容。
get-childItem temp\*.* -recurse |
get-content |
foreach-object {$_.replace($stringToFind1, $stringToPlace1)} |
set-content [original filename]
我可以从原始 get-childItem 获取文件名以在 set-content 中使用它吗?
为每个文件添加处理:
get-childItem *.* -recurse | % `
{
$filepath = $_.FullName;
(get-content $filepath) |
% { $_ -replace $stringToFind1, $stringToPlace1 } |
set-content $filepath -Force
}
关键点:
$filepath = $_.FullName;
— 获取文件路径(get-content $filepath)
— 获取内容并关闭文件set-content $filepath -Force
— 保存修改的内容您可以简单地使用$_
,但您也需要foreach-object
在每个文件周围加上一个。虽然@akim 的回答会起作用,但使用$filepath
是不必要的:
gci temp\*.* -recurse | foreach-object { (Get-Content $_) | ForEach-Object { $_ -replace $stringToFind1, $stringToPlace1 } | Set-Content $_ }