我試圖在某個目錄結構中替換所有文件的內容。閱讀所有文件,更改內容,再次保存
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
。雖然@阿基姆的答案會工作,使用$filepath
是不必要的:
gci temp\*.* -recurse | foreach-object { (Get-Content $_) | ForEach-Object { $_ -replace $stringToFind1, $stringToPlace1 } | Set-Content $_ }
我認爲你錯過了一個右括號。 – 2012-08-03 13:05:59
將您的答案與@ akim的結合起來 – 2012-08-03 13:15:39
@BorisCallens:謝謝,修正! – 2012-08-03 13:26:49
腳本要求一個參數,當第一的foreach後跟一個換行符。通過將第一個大括號移動到同一行來解決此問題,但現在它說$ filepath參數的$不被識別 – 2012-08-03 11:44:31
示例已被修正:添加'和'$ _' – Akim 2012-08-03 11:50:08
將您的答案與@ Dan's結合起來。將你的標記標記爲添加上下文的答案。 Thx :) – 2012-08-03 13:16:16