我已经编写了一个PowerShell脚本来对XML文件进行修改,但是由于并非每个XML文件都需要更新,因此我不想不必要地写入该文件。我(或脚本)进行修改后,当前正在将变量设置为$true
:
[bool]$Modified = $false
[string]$PathToXML = $env:UserProfile + '\test.xml'
$XMLObject = New-Object XML
$XMLObject.Load($PathToXML)
If($XMLObject.property.otherproperty -ne 'Goldfish')
{
$XMLObject.property.otherproperty = 'Goldfish'
[bool]$Modified = $true
}
if($Modofied -eq $true) { $XMLObject.Save($PathToXML) }
但是,这让我感到奇怪:PowerShell或.NET中是否有内置属性或方法可以自动跟踪对已加载的XML对象的修改并返回一个布尔值,该值指示是否已加载XML对象被修改了吗?像这样:
[string]$PathToXML = $env:UserProfile + '\test.xml'
$XMLObject = New-Object XML
$XMLObject.Load($PathToXML)
# Checking $XMLObject.IsChanged would return false
If($XMLObject.property.otherproperty -ne 'Goldfish')
{
$XMLObject.property.otherproperty = 'Goldfish'
# A this point $XMLObject.IsChanged is now true
}
if($XMLObject.IsChanged) { $XMLObject.Save($PathToXML) }
我可以提供的最接近的示例是Microsoft.ConfigurationManagement.ApplicationManagement.Application类中的IsChanged属性:对XML进行反序列化并更改任何属性后,IsChanged
属性将自动从从虚假到真实。
答案 0 :(得分:0)
为什么你不能像下面这样。
If($XMLObject.property.otherproperty -ne 'Goldfish')
{
$XMLObject.property.otherproperty = 'Goldfish'
$XMLObject.Save($PathToXML)
}
在if
语句中进行保存。