繁体   English   中英

PowerShell将XML属性添加到变量

[英]PowerShell to Add XML Attribute to Variable

我有一个XML文件,并且想使用PowerShell基于变量搜索节点,然后将该属性设置为另一个可以使用的变量。

我的XML保存在C:\\ example.xml中,代码如下:

<?xml version="1.0" encoding="UTF-8"?>
<Portal>
<A23062013 Current="13" lastweek="12" />
<A24062013 Current="13" lastweek="12" />
</Portal>

Portal节点内XML节点的内容实际上是ddMMyyy格式的日期,并且它们的前缀是A,如上所述。

我的Powershell代码如下:

$date = (Get-Date).AddDays(-1).ToString('ddMMyyyy')
$pre = "A"
$completedate = "$pre$date"
[xml] $file = get-content "C:\example.xml"
$xmlValuePrevious = $file.SelectNodes ('$completedate') | select lastweek
$xmlValueCurrent = $file.SelectNodes ('$completedate') | select Current
Write-Host "$xmlValuePrevious $xmlValueCurrent"

当前,它在第5行和第6行引发错误,提示:

表达式或语句中出现意外的标记'('。

当我刚接触PS时,可能缺少一些容易的事情,但是我已经搜索了很多年,但找不到有关此问题的任何具体信息。

谢谢,广告

您的代码有几个问题:

  • 删除SelectNodesSelectNodes括号之间的空间。
  • 如果要在字符串中扩展变量,请使用双引号。 或者,如果只想传递变量,请完全删除引号。
  • 要在XML树中的任何位置选择节点,您需要在节点名称前添加// 在XPath表达式中仅使用节点名称将在当前节点中仅选择具有该名称的节点。

更改此:

$xmlValuePrevious = $file.SelectNodes ('$completedate') | select lastweek
$xmlValueCurrent = $file.SelectNodes ('$completedate') | select Current

到这个:

$xmlValuePrevious = $file.SelectNodes("//$completedate") | select lastweek
$xmlValueCurrent = $file.SelectNodes("//$completedate") | select Current

自从Ansgar已经准备好解释您的代码的问题之后,我就不再赘述了。

但是,对于访问xml结构,您也可以使用点符号(对于初学者来说更容易一点):

$xmlValuePrevious = $file.Portal.$completedate.lastweek
$xmlValueCurrent = $file.Portal.$completedate.current

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM