使用PowerShell替換XML文件中的文本


昨天,我在一個客戶現場工作,那裏有一個與外部網絡隔離的Windows伺服器。不允許在該機器上安裝任何第三方軟件。

PowerShell腳本

然而,我被交付了一項任務,要將所有XML文件名從“我的報告”換成“我的報告(新)”。原始文件,temp.xml,是這樣的:

    <ReportList>
      <Report Name="My Report">
      </Report>
    </ReportList>

預期的輸出文件,temp-new.xml,應有這樣的結構:

    <ReportList>
      <Report Name="My Report (New)">
      </Report>
    </ReportList>

沒有專門工具的訪問權限,並面對手動編輯數百個文件的前景,我轉向了PowerShell來編寫腳本。以下是完成此任務的幾行代碼:

步驟1:從我的測試文件夾中加載所有XML文件

    $files = Get-ChildItem C:\Users\victorleung\tw\Desktop\Test -Recurse -Include *.xml

步驟2:通過在原始名稱後添加”(新)“來修改所有報告名稱

    $xmldata = [xml](Get-Content $file);
    $name = $xmldata.ReportList.Report.GetAttribute("Name");
    $name = $name + " (New)";
    $xmldata.ReportList.Report.SetAttribute("Name", $name);
    $xmldata.Save($file)

步驟3:將文件名從temp.xml 改成 temp-new.xml

    Get-ChildItem *.xml | Rename-Item -NewName { $_.Name -Replace '.xml$','-new.xml' }

就是這樣!所有文件都已被更改。開心編碼!😃