PowerShell脚本循环遍历每个文件并执行查找和替换

时间:2015-08-03 14:10:12

标签: powershell

我当前的代码是

Param(
  [string]$filePath = "C:\",
  [string]$logFileFind = "error.log",
  [string]$logFileReplace ="ThisHasBeenReplaced.log" 
)


($configFile = Get-ChildItem -Recurse -Force $filePath -ErrorAction SilentlyContinue | Where-Object { ($_.PSIsContainer -eq $false) -and  ( $_.Name -like "*.config") } 

它工作正常,并给我文件列表我想知道如何我可以通过这些文件,找到并替换某些单词,当我移动通过环境和路径不会相同。我的powershell知识非常有限,我尝试将其添加到脚本的末尾。

ForEach-Object{(Get-Content $configFile) -replace $logFileFind , $logFileReplace | Set-Content $configFile})

这不起作用,我想知道是否有人知道我能做些什么来使它工作。

提前致谢!

1 个答案:

答案 0 :(得分:1)

您总是在foreach循环中访问$configFile(可能是System.Array),而不是实际元素。试试这个:

$configFile | foreach { (get-content $_.FullName -Raw) -replace $logFileFind , $logFileReplace | Set-Content $_.FullName }

以下是一个完整的例子:

Get-ChildItem -Recurse -force $filePath -ea 0 |
 where { ($_.PSIsContainer -eq $false) -and ( $_.Name -like "*.config") } | 
 foreach { 
   (gc $_.FullName -raw) -replace $logFileFind , $logFileReplace | sc $_.FullName 
 }