使用布尔参数从 PowerShell 调用 .NET 方法

Calling .NET method from PowerShell with boolean parameter

我正在尝试将 XML 节点从一个文档导入到另一个文档。我在 XmlDocument 上使用两个参数调用 ImportNode 方法 - 节点和布尔参数。

...
$connectionString = $anotherWebConfig.SelectSingleNode("//add[@name='ConnectionString']")
$WebConfig.ImportNode($connectionString, $True)
$WebConfig.SelectSingleNode("//connectionStrings").AppendChild($connectionString)

但我遇到了错误

Exception calling "AppendChild" with "1" argument(s): "The node to be inserted is from a different document context."

我知道导入肯定有问题。我尝试将 $True 参数更改为 1、0、10 并将其删除,但仍然无济于事。令我惊讶的是,即使我使用无效参数调用此方法,它也会毫无例外地通过。

使用布尔参数从 powershell 调用 .NET 方法的正确方法是什么?

您似乎在这里误诊了问题 - 问题不是布尔参数,而是您尝试附加 original 节点而不是导入节点的事实:

$WebConfig.ImportNode($connectionString, $True) # <-- great effort to import node
$WebConfig.SelectSingleNode("//connectionStrings").AppendChild($connectionString)
#                                                                      ^
#                                                                      |
#                                                       Yet still appending the original 

将导入的节点(从 ImportNode() 返回)分配给一个变量,并引用 that 作为 AppendChild() 的参数:

$ImportedNode = $WebConfig.ImportNode($connectionString, $True)
$WebConfig.SelectSingleNode("//connectionStrings").AppendChild($ImportedNode)