使用PowerShell脚本查找和替换具有特定扩展名的所有文件 [英] PowerShell Script to Find and Replace for all Files with a Specific Extension
问题描述
我在Windows Server 2008上有几个配置文件,像这样嵌套:
pre code C:\Projects\Project_1\ project1.config
C:\Projects\Project_2\project2.config
< add key =Environmentvalue =在我的配置中我需要做一个字符串替换, 开发/>
会变成:
< add key =Environmentvalue =Demo/>
我想过使用批处理脚本,但没有好的办法来做到这一点,我听说使用PowerShell脚本,您可以轻松执行此操作。我找到了find / replace的例子,但是我希望能够遍历C:\Projects目录下的所有文件夹,并找到任何以.config扩展名结尾的文件。当它找到一个,我希望它取代我的字符串值。
有什么好的资源来找到如何做到这一点或任何PowerShell的大师,可以提供一些洞察力? / p>
这里首先尝试一下我的头脑。
$ configFiles = Get-ChildItem。 * .config -rec
foreach($ configFiles中的$文件)
{
(Get-Content $ file.PSPath)|
Foreach-Object {$ _ -replaceDev,Demo} |
Set-Content $ file.PSPath
}
I have several configuration files on Windows Server 2008 nested like such:
C:\Projects\Project_1\project1.config
C:\Projects\Project_2\project2.config
In my configuration I need to do a string replace like such:
<add key="Environment" value="Dev"/>
will become:
<add key="Environment" value="Demo"/>
I thought about using batch scripting, but there was no good way to do this, and I heard that with PowerShell scripting you can easily perform this. I have found examples of find/replace, but I was hoping for a way that would traverse all folders within my C:\Projects directory and find any files that end with the '.config' extension. When it finds one, I want it to replace my string values.
Any good resources to find out how to do this or any PowerShell gurus that can offer some insight?
Here a first attempt at the top of my head.
$configFiles = Get-ChildItem . *.config -rec
foreach ($file in $configFiles)
{
(Get-Content $file.PSPath) |
Foreach-Object { $_ -replace "Dev", "Demo" } |
Set-Content $file.PSPath
}
这篇关于使用PowerShell脚本查找和替换具有特定扩展名的所有文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!