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 回答