【问题标题】:XML Xpath with variable to remove node [duplicate]带有变量的XML Xpath以删除节点[重复]
【发布时间】:2025-12-23 16:15:07
【问题描述】:

感谢@Mathias R. Jessen 的帮助,我能够让它工作,但我想做的是在脚本顶部添加一个变量来设置模型名称,但我没有任何运气。有什么想法吗?

$modelselect = "HP EliteBook x360 830 G7"

$file = "C:\Temp\test1.xml"
$xmlfile = [XML](Get-Content $file)
$item = Select-Xml $xmlFile -XPath '//Model[./ModelName = "$modelselect"]'

foreach($node in $item.Node)
{
$node.ParentNode.RemoveChild($node)
}

$xmlFile.Save($file)

【问题讨论】:

  • 表达式'//Model[./ModelName = "$modelselect"]' 的外部单引号不允许变量扩展。 "//Model[./ModelName = '$modelselect']" 应该可以工作。
  • 你看到last update to the previous answer了吗?请注意,我在字符串文字中交换了 '" 以允许扩展 $ModelName
  • @Mathias R. Jessen 对不起,我没有。我去检查一下。谢谢,感谢您的所有帮助!第一次使用 XML。
  • 简而言之:只有"..."字符串(双引号,称为可扩展字符串)在PowerShell中执行字符串插值(变量值的扩展),而不是'...'字符串(单引号,称为 逐字字符串):请参阅this answer 了解 PowerShell 的可扩展字符串 的概述和this answer 了解 PowerShell 的一般概述 字符串文字.

标签: powershell


【解决方案1】:

下面的工作,谢谢大家!

"//Model[./ModelName = '$modelselect']"

【讨论】: