【问题标题】:Config Update - PowerShell配置更新 - PowerShell
【发布时间】:2022-01-01 05:19:15
【问题描述】:

希望有人能指出我正确的方向。

背景:

环境是 Windows 10 - 我需要为我们的用户更新配置文件中的一行,从数字 IP 到字符串。每个设备都可能在脚本的定义路径中存在多个配置文件,并且存在不同的先前用户配置文件。为此,我将脚本作为通配符来更新所有定位的配置,以更新同一行,使其统一并避免部署后的冲突。 目前,该脚本可以替换这些值,但是当脚本拾取其他配置时,它们会被合并并为找到的每个配置重新输入。

当前形式的脚本

((Get-Content -Path "C:\Program Files\ProgramX\config\brand-protocol-port-*-config.ext" -Raw) -replace 'X.X.X.X','VALUE') |
    Set-Content -Path " C:\Program Files\ProgramX\config\brand-protocol-port-*-config.ext "
Get-Content -Path " C:\Program Files\ProgramX\config\brand-protocol-port-*-config.ext "

结果是,如果有 John Smith 和 John Walker 的配置文件 - 脚本运行后,文件会按预期更新,但不是更新 2 个单独的配置文件,而是更新它们,然后在每个实例中添加在一起更新的文件彼此存在。

任何指针表示赞赏!

【问题讨论】:

    标签: windows powershell configuration updates


    【解决方案1】:

    您需要的是使用循环,以便可以单独处理每个文件:

    # since we're using the regex `-replace` operator, the dots need to be escaped
    $ipToFind    = [regex]::Escape('X.X.X.X')
    $replaceWith = 'VALUE'
    Get-ChildItem -Path 'C:\Program Files\ProgramX\config' -Filter 'brand-protocol-port-*-config.ext' -File | ForEach-Object {
        (Get-Content -Path $_.FullName -Raw) -replace $ipToFind, $replaceWith | Set-Content -Path $_.FullName
    }
    

    【讨论】:

    • 工作完美,谢谢!
    猜你喜欢
    • 2018-10-24
    • 2023-03-22
    • 2011-01-28
    • 1970-01-01
    • 1970-01-01
    • 2018-02-15
    • 1970-01-01
    • 2012-08-13
    • 2012-07-06
    相关资源
    最近更新 更多