【问题标题】:Replacing a line of text in .ini using PowerShell使用 PowerShell 替换 .ini 中的一行文本
【发布时间】:2015-10-30 14:41:28
【问题描述】:

您好,我正在尝试在 PowerShell ISE 中运行脚本来替换 .ini 文件中的一行文本。

(Get-Content C:\ProgramData\Nuance\NaturallySpeaking12\nssystem.ini) | ForEach-Object { $_ -replace "Default NAS Address=","Default NAS Address=BHPAPPDGN01V" } | Set-Content C:\ProgramData\Nuance\NaturallySpeaking12\nssystem.ini

这个脚本可以工作,但是当我多次运行它时,.ini 文本不断被添加到行尾,给了我一堆垃圾。

示例:运行脚本 4 次“默认 NAS 地址=BHPAPPDGN01VBHPAPPDGN01VBHPAPPDGN01VBHPAPPDGN01V"

【问题讨论】:

    标签: ini powershell-ise


    【解决方案1】:

    试试这个:

    (Get-Content C:\ProgramData\Nuance\NaturallySpeaking12\nssystem.ini) | ForEach-Object { $_ -replace 'Default NAS Address=.*','Default NAS Address=BHPAPPDGN01V' } | Set-Content C:\ProgramData\Nuance\NaturallySpeaking12\nssystem.ini
    

    我只是尝试使用正则表达式来选择 = 后面的所有内容。

    【讨论】:

    • 非常棒的简单命令,非常有用!谢谢。
    【解决方案2】:

    替换

    "-替换"默认NAS地址="

    "-replace "默认 NAS 地址=[A-Z0-9]*"

    【讨论】:

      【解决方案3】:

      我不喜欢上面的建议,所以这是我的解决方案,以防有人从 Google 偶然发现它有用。

      test.ini 的内容

      [Other Parameter] = Something
      [My Parameter] = What I wouldnt give for a change of heart
      [Other Parameter] = Nothing
      

      我的解决方案:

      $MyString = Get-Content "C:\Test_Script\test.ini"
      $NewString = $MyString.replace("[My Parameter] = What I wouldnt give for a change of heart","[My Parameter] = I gave my heart for a piece of string")
      Set-Content -Path "C:\Test_Script\test.ini"  -Value $NewString
      

      更改了 test.ini 的内容

      [Other Parameter] = Something
      [My Parameter] = I gave my heart for a piece of string
      [Other Parameter] = Nothing
      

      【讨论】:

        猜你喜欢
        • 2013-05-14
        • 1970-01-01
        • 2021-01-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-10-06
        • 2015-07-27
        • 2015-10-28
        相关资源
        最近更新 更多