用于查找和替换具有特定扩展名的所有文件的 PowerShell 脚本 [英] PowerShell Script to Find and Replace for all Files with a Specific Extension

查看:34
本文介绍了用于查找和替换具有特定扩展名的所有文件的 PowerShell 脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Windows Server 2008 上嵌套了几个配置文件,如下所示:

I have several configuration files on Windows Server 2008 nested like such:

C:ProjectsProject_1project1.config

C:ProjectsProject_2project2.config

在我的配置中,我需要像这样进行字符串替换:

In my configuration I need to do a string replace like such:

<add key="Environment" value="Dev"/>

将变成:

<add key="Environment" value="Demo"/>

我想过使用批处理脚本,但没有好的方法可以做到这一点,而且我听说使用 PowerShell 脚本可以轻松执行此操作.我找到了查找/替换的示例,但我希望有一种方法可以遍历 C:Projects 目录中的所有文件夹并找到以.config"扩展名结尾的任何文件.当它找到一个时,我希望它替换我的字符串值.

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.

有什么好的资源可以了解如何做到这一点,或者任何可以提供一些见解的 PowerShell 专家?

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆