找不到“ WriteElementString”的重载和参数计数:“ 2”

时间:2019-02-14 17:53:25

标签: powershell

我正在创建一个xml文件并使用“ get-service”,并尝试获取正在运行的服务的名称和状态。如果仅使用“ get-service -name”然后使用服务名称,我将获取所需的数据。但是,它不会以这种方式写入xml文件。因此,我尝试使用“ get-service -name”名称服务” |选择对象名称,状态。这将引发“找不到重载...”

有什么建议吗?

我试图仅使用get-service“服务名称”,但是再次写入xml文件的只是服务名称。我试图用管道输送选择对象名称,状态,并且如上所述抛出了错误。

# Set the File Name Create The Document
$XmlWriter = [System.XML.XmlWriter]::Create("G:\TestEnvironmentScript\$env:COMPUTERNAME-State.xml", $xmlsettings)

# Write the XML Decleration and set the XSL
$xmlWriter.WriteStartDocument()
$xmlWriter.WriteProcessingInstruction("xml-stylesheet", "type='text/xsl' href='style.xsl'")

# Start the Root Element
$xmlWriter.WriteStartElement("morestuff")

 $xmlWriter.WriteStartElement("ServerInformation") # <-- Start <Object>

 $xmlWriter.WriteElementString("ServerName",$env:COMPUTERNAME)

 $xmlWriter.WriteElementString("StateCheckTime",(Get-Date -Format G))

$xmlWriter.WriteStartElement("Services") # <-- Start <SubOject>

$XmlWriter.WriteElementString("nameofsomeservice",(Get-Service -Name Name-of-Some-Service | Select-Object Name, Status))

    $xmlWriter.WriteEndElement() # <-- End <Object>

$xmlWriter.WriteEndElement() # <-- End <Root> 

# End, Finalize and close the XML Document
$xmlWriter.WriteEndDocument()
$xmlWriter.Flush()
$xmlWriter.Close()

我只希望xml文档包含名称和状态。我可能只是对这个状态感到满意。...

1 个答案:

答案 0 :(得分:0)

抛出“ WriteElementString”错误,因为正在传递数据 (Get-Service -Name Name-of-Some-Service | Select-Object Name, Status)就像

Name        Status
----        ----
ServiceName Running

如果将服务结果放入变量中,则可以引用每个元素并获得所需的结果

# Set the File Name Create The Document
$XmlWriter = [System.XML.XmlWriter]::Create("G:\TestEnvironmentScript\$env:COMPUTERNAME-State.xml", $xmlsettings)

# Write the XML Decleration and set the XSL
$xmlWriter.WriteStartDocument()
$xmlWriter.WriteProcessingInstruction("xml-stylesheet", "type='text/xsl' href='style.xsl'")

# Start the Root Element
$xmlWriter.WriteStartElement("morestuff")

 $xmlWriter.WriteStartElement("ServerInformation") # <-- Start <Object>

 $xmlWriter.WriteElementString("ServerName",$env:COMPUTERNAME)

 $xmlWriter.WriteElementString("StateCheckTime",(Get-Date -Format G))

$xmlWriter.WriteStartElement("Services") # <-- Start <SubOject>

$serviceState = (Get-Service -Name Name-of-Some-Service | Select-Object Name, Status)
$XmlWriter.WriteElementString("nameofsomeservice", ($serviceState.Name, $serviceState.Status))

    $xmlWriter.WriteEndElement() # <-- End <Object>

$xmlWriter.WriteEndElement() # <-- End <Root> 

# End, Finalize and close the XML Document
$xmlWriter.WriteEndDocument()
$xmlWriter.Flush()
$xmlWriter.Close()