【发布时间】:2020-08-22 16:10:04
【问题描述】:
我在我的 Powershell 脚本中的 Jobs 中遇到了 XmlElements 的奇怪行为。 $CommandConfiguration 是一个带有嵌套元素的 XML 元素。这些元素存在于作业范围之外的脚本中,这已经过测试和调试。考虑一下这段代码:
if($CommandConfiguration.ChildNodes.Name -contains "DomainCheck"){
Write-Host ChildNode exists # this is executed
}
$Jobs += Start-Job -Name "WMI-Job" -ScriptBlock {
$th = $Using:TargetHost
$cc = $Using:CommandConfiguration
$creds = $Using:Creds
if($cc.ChildNodes.Name -contains "DomainCheck"){
Write-Host ChildNode exists # this is NOT executed
}
...
显然,为什么子节点存在于作业之外而不存在于作业内部?我错过了什么吗?
感谢您帮助我!
【问题讨论】:
-
为了完整起见,您确实使用
Receive-Job之类的东西来实际获得作业输出,对吗?否则Write-Host无论如何也不会显示太多。 -
是的,我正在等待作业失败或完成,然后再收到。输出 write-host 应该给出的结果不显示。
-
取决于
CommandConfiguration是什么,它可能无法正确序列化以在using中有用,但这是推测。查看($using:CommandConfiguration).GetType()输出的内容,而不是块外的类型。任何比string更复杂的东西都会冒着不能完全像以前那样结束的风险,并且脚本或魔法属性等某些便利可能会消失。一个简单的 XML 元素在我的测试中有效,但你永远不知道。 -
@JeroenMostert 在 Job 之外它是一个 XMLElement,在它内部是一个 System.Management.Automation.PSObject。有什么办法可以解决这个问题吗?
-
不,这只是意味着 PowerShell 已将其序列化为无法简单转换为字符串的内容(我不知道具体是什么),因此我提出的反序列化方法失败了。您始终可以将其强制为扁平字符串 (
$stringCommandConfiguration = $CommandConfiguration.InnerXml; ...$cc = [xml] $using:stringCommandConfiguration)。
标签: xml powershell jobs using