【发布时间】:2018-07-17 15:35:28
【问题描述】:
我正在从一些 XML 数据中检索一个文本字符串,然后尝试用其他内容替换该字符串。我使用的代码是:
$newstring = "mystring"
$bar = Get-Gpo -Name "My GPO"
$gpoid = $bar.Id.ToString()
$drivesxml = New-Object XML
$drivesxml.Load("\\mydomain.co.uk\sysvol\mydomain.co.uk\Policies\{gpoid}\User\Preferences\Drives\drives.xml")
$oldpath = $drivesxml.Drives.Drive.Properties.Path[0]
$oldlabel = $drivesxml.Drives.Drive.Properties.Label[0]
#1
[string]$newtemppath = $oldpath -replace "Oldstring$", "$newstring"
[string]$newtemplabel = $oldlabel -replace "^Oldstring", "$newstring"
#2
$drivesxml.Drives.Drive.Properties.Path[0] = $newtemppath
$drivesxml.Drives.Drive.Properties.Label[0] = $newtemplabel
#3
$drivesxml.Save("\\mydomain.co.uk\sysvol\mydomain.co.uk\Policies\{gpoid}\User\Preferences\Drives\drives.xml")
它很好地从 sysvol 中检索 XML,如果我查询 $oldpath 和 $oldlabel,它们在点 1 处包含来自 XML 的预期文本。
如果我在 #2 查询 $newtemppath 和 $newtemplabel,则字符串按预期返回,并修改了文本,因此“Oldstring”的实例已被“mystring”替换。
在#3,如果我查询$drivesxml.Drives.Drive.Properties.Path[0] 和$drivesxml.Drives.Drive.Properties.Label[0],我希望它们返回与$newtemppath 和$newtemplabel 变量相同的内容,但它们会继续返回其原始值。
保存 XML 后,如果我再次查询它,内容并没有改变。
谁能看到我在 #2 和 #3 之间的分配中可能做错了什么?
【问题讨论】:
标签: xml powershell