请求编写PowerShell脚本为指定VM的XML配置文件插入配置项
PowerShell Script to Insert Log Configuration Nodes into XML File
Got it, here's a PowerShell script that'll handle inserting those two log configuration keys exactly where you need them — between <add key="LogFilePath"/> and <add key="FtpEnabled"/> under your Run1, Run2, and any other Run* nodes in your XML config:
# Replace this with the actual path to your XML configuration file $xmlPath = "C:\Path\To\Your\ConfigFile.xml" # Load the XML file $xml = [xml](Get-Content $xmlPath) # Target all nodes starting with "Run" (matches Run1, Run2, etc.) $runNodes = $xml.SelectNodes("//*[starts-with(local-name(), 'Run')]") foreach ($runNode in $runNodes) { # Find the LogFilePath node within the current Run node $logFilePathNode = $runNode.SelectSingleNode("./add[@key='LogFilePath']") if ($logFilePathNode -eq $null) { Write-Warning "Skipping $($runNode.Name) - LogFilePath node not found" continue } # Find the FtpEnabled node to confirm insertion position (optional but safe) $ftpEnabledNode = $runNode.SelectSingleNode("./add[@key='FtpEnabled']") if ($ftpEnabledNode -eq $null) { Write-Warning "Skipping $($runNode.Name) - FtpEnabled node not found" continue } # Create the LogFileSizeLimit node $sizeLimitNode = $xml.CreateElement("add") $sizeLimitNode.SetAttribute("key", "LogFileSizeLimit") $sizeLimitNode.SetAttribute("value", "40") # Create the LogFileArchiveCount node $archiveCountNode = $xml.CreateElement("add") $archiveCountNode.SetAttribute("key", "LogFileArchiveCount") $archiveCountNode.SetAttribute("value", "2") # Insert both nodes RIGHT AFTER LogFilePath (so they land between LogFilePath and FtpEnabled) $runNode.InsertAfter($sizeLimitNode, $logFilePathNode) $runNode.InsertAfter($archiveCountNode, $sizeLimitNode) } # Save the modified XML back to the file try { $xml.Save($xmlPath) Write-Host "Successfully updated XML configuration file at $xmlPath" -ForegroundColor Green } catch { Write-Error "Failed to save XML file: $_" }
Key Notes & Safety Tips:
- Backup First: Always make a copy of your original XML file before running this script — just in case!
- Path Replacement: Don't forget to replace the
$xmlPathvalue with your actual config file path. - Namespace Handling: If your XML uses a namespace, you'll need to adjust the XPath queries to include it. For example, if your root has
xmlns="http://example.com/config", you'll need to define a namespace manager and use it inSelectNodes/SelectSingleNode. - Validation: After running the script, open your XML file to verify the new nodes are in the correct position between
LogFilePathandFtpEnabled.
内容的提问来源于stack exchange,提问作者Timmy Aroyewun
相关产品推荐
相关产品推荐

