首页 > 解决方案 > 方法调用失败,因为 [System.String] 不包含名为“AppendChild”的方法

问题描述

突然,这段代码不再工作了。我正在尝试用谷歌搜索,但似乎找不到任何解决方案来解决这个问题。

我不能只做

[xml]($deploymentXml.configuration.services).AppendChild($newService)

或者

$deploymentServicesNode = [xml]$deploymentXml.configuration.services
$deploymentServicesNode.AppendChild($newService)

有谁知道发生了什么以及为什么这不再起作用?


部署.xml

<?xml version="1.0" encoding="utf-8"?>
<configuration description="Services deployment server">
    <services>
    </services>
</configuration>

方法调用失败,因为 [System.String] 不包含名为“AppendChild”的方法。在 F:\USB\host.ps1:153 char:9 + $deploymentXml.configuration.services.AppendChild($service ... + ~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [ ],RuntimeException + FullyQualifiedErrorId:MethodNotFound

host.ps1部分

#Location of the file
$deploymentFile = $PSScriptRoot + "\USB\Configuration\Deployment.xml";
$deploymentXml = [xml](Get-Content $deploymentFile);

# check if we got a file, if not do nothing.
if ($deploymentXml) {
    Write-Verbose "deployment xml: $deploymentFile"

    foreach($service in $Services) {
        # Create the new service
        $newService = $deploymentXml.CreateElement("service");
        $deploymentXml.configuration.services.AppendChild($newService)

        Write-Verbose "Adding service: $service"

        $newService.SetAttribute("name", $service);   
    }

    $deploymentXml.Save($deploymentFile);
}

标签: xmlpowershell

解决方案


在获取您的 XML 内容之前,请尝试添加以下内容:

$deploymentFile = $PSScriptRoot + "\USB\Configuration\Deployment.xml";
[System.Xml.XmlDocument]$deploymentXml = New-Object System.Xml.XmlDocument
$deploymentXml = [xml](Get-Content $deploymentFile);

我遇到了一些在某些环境中未设置类型的问题,即 SQL 作业 PowerShell 步骤。


推荐阅读