命名空间声明后的管道 PowerShell XML 对象



我有一段PowerShell代码,它有效。

$xml = [xml](gc '.test.xml')
$ns = New-Object Xml.XmlNamespaceManager $xml.NameTable
$ns.AddNamespace("ns", "randomnamespace")
$nodes = $xml.SelectNodes("//ns:tag", $ns)
# print all nodes
foreach ($node in $nodes) {
Write-Host $node.anotherTag " - " $node.anotherTag.Substring(0,7)
}

我想把它放在一行中以将其用作PowerShell命令,因为我无法更改执行策略。

我尝试了以下方法:

$xml = [xml](gc '.test.xml') | $ns = New-Object Xml.XmlNamespaceManager $_.NameTable | $ns.AddNamespace('ns', 'tag') | $xml.selectNodes('//ns:anotherTag', $ns) | foreach {Write-Host $_.anotherTag' - ' $_.anotherTag(0,7)}"

但我收到错误消息

表达式仅允许作为管道中的第一个元素...名称表 |$ns。AddNamespace('ns',..(

并且我无法在读取 XML 文件之前声明命名空间。

有什么办法可以让它工作吗?

不要使用管道|,而是使用分号;

最新更新