powershell - 在文件中的引号之间替换字符串内容

标签 powershell

我进行了此循环以迭代一些我要替换内容的文件。

我要替换的内容是一个字符串,看起来像这样:foo="1"

我需要您的帮助的是如何查找字符串(我猜是正则表达式)并使用新值更新文件,例如2

$files = Get-ChildItem -Recurse -Filter "*.config"

foreach ($file in $files)
{
    Get-Content $file.FullName
}

Read-Host

最佳答案

从问题的示例代码中,我假设您正在尝试更新.NET配置文件(即web.configapp.config文件)。

鉴于这些文件实际上是XML文件,您可能需要这样对待它们:

$files = Get-ChildItem -Recurse -Filter "*.config"

foreach ($file in $files)
{
    # Create an XmlDocument object from the file
    $configXml = [xml](Get-Content $file.FullName)

    # Find all the nodes in the document
    $xmlNodes  = $configXml.SelectNodes('//*')

    # Keep track of whether we make changes or not
    $changeCount = 0

    foreach($node in $xmlNodes)
    {
        # Check if node has a "foo" attribute
        if($node.HasAttribute('foo'))
        {
            # Set 2 as the value
            $node.SetAttribute('foo',2)
            $changeCount++
        }
    }

    if($changeCount)
    {
        # At least one node was updated, save to file
        $configXml.Save($file.FullName)
    }
}

关于powershell - 在文件中的引号之间替换字符串内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34948449/

相关文章:

windows - 通过 powershell 脚本自定义协议(protocol)处理程序

windows - 观看后自动标记电影文件

regex - 协助使用 PowerShell 中的可选正则表达式

powershell - Azure-SSMS-PowerShell

.net - PowerShell表单关闭输出 “Cancel”

macos - 在 Mac 上更新 PowerShell 帮助

Powershell:排序百分比数字

azure - Powershell - Get-AzureADAuditSignInLogs 多个筛选器

regex - Powershell以字符串模式显示的5位数字格式

jquery - 使用 Powershell Where-Object 获取 src img