Powershell 为什么会出错;System.String不包含名为';追加儿童'&引用;

Powershell 为什么会出错;System.String不包含名为';追加儿童'&引用;,powershell,Powershell,为什么此PowerShell脚本不起作用: [xml]$xml='' $newproduct=$xml.CreateElement('product') $attr=$xml.CreateAttribute('code')) $attr.Value='id1' $newproduct.Attributes.Append($attr) $products=$xml.products $products.AppendChild($newproduct) 错误是 方法调用失败,因为[System.S

为什么此PowerShell脚本不起作用:

[xml]$xml=''
$newproduct=$xml.CreateElement('product')
$attr=$xml.CreateAttribute('code'))
$attr.Value='id1'
$newproduct.Attributes.Append($attr)
$products=$xml.products
$products.AppendChild($newproduct)
错误是

方法调用失败,因为[System.String]不包含名为“AppendChild”的方法。
第1行字符:1
+$products.AppendChild($newproduct)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+CategoryInfo:InvalidOperation:(:)[],运行时异常
+FullyQualifiedErrorId:MethodNotFound
如果我替换

$products=$xml.products

$products=$xml.SelectSingleNode(“//products”)

它会起作用,但我想知道为什么第一个语法不起作用,因为它对我来说是不合逻辑的
$xml.products
应该是有效的xml对象,因此提供方法
AppendChild()

$xml.products
不引用
products
节点本身,而是引用
products
节点的内容。由于
products
为空,因此其计算结果为空字符串

要访问
产品
节点,您还可以使用:

$Products = $xml.FirstChild 
$Products.AppendChild($newproduct)
或者,更具体地说:

$Products = $xml.ChildNodes.Where({$_.Name -eq "products"}) |Select-Object -First 1
$Products.AppendChild($newproduct) 
但是
SelectSingleNode()
可能会很好地为您服务

$xml.configuration.SelectSingleNode("connectionStrings").AppendChild($newnode)
这样可以很好地工作,但是有一个有趣且肮脏的黑客:给定这个空节点:

  <connectionStrings>    
  </connectionStrings>
给出一个“
方法调用失败,因为[System.String]不包含名为'AppendChild'的方法”
”错误

但这是:

  <connectionStrings>
        <!-- random comment -->
  </connectionStrings>


工作正常

我获取方法调用失败,因为[System.Xml.xmlement]不包含名为“Where”的方法。5.0这不起作用,但另一个选择SingleNode的答案救了我@McVitas感谢您的提醒,如果google将您带到这里,因为[System.String]不包含名为“StartsWith”或“IndexOf”的方法或它实际拥有的任何其他东西,这可能是因为您有类似于
$val=“DefinitelyAString”
的东西,并且正在尝试使用类似
$val::IndexOf(“ef”)
的东西。这个超级可怕的错误应该是“使用
$val.IndexOf(“ef”)
。谢谢@StingyJack,这正是我要找的。
  <connectionStrings>
        <!-- random comment -->
  </connectionStrings>