gpt4 book ai didi

powershell - Start-Job 将 XML 对象传递给 -ArgumentList 在 Powershell V2 和 V3 中工作方式不同

转载 作者:行者123 更新时间:2023-12-02 20:25:42 25 4
gpt4 key购买 nike

我正在使用 Powershell v3 在 Windows Server 2012 上测试我的应用程序的部署脚本。该脚本在使用 Powershell v2 的 Win Server 2008 R2 和 Win 7 上运行良好。我现在遇到的问题是我无法访问通过 -ArgumentList 传递的 XML 变量的属性。

我已经能够在 Win 7 和 Win Server 2012 上使用 Powershell v3 在一个简单的脚本中重现该问题,该脚本不包含任何 SharePoint、IIS 以及我的主脚本所包含的其他内容。

脚本(我想我从现在找不到的类似问题中借用了这个):

$xml = [xml] (Get-Content (Get-Item (".\input.xml")))
$foobar = $xml.Stuff.FooBars.Foobar

$ScriptBlock = {
$foobar = $args[0]

write-host "Inside the job..."
write-host ("Foobar : "+$foobar)
write-host ("Foobar.Foo : "+$foobar.Foo)
}

write-host "Outside the job..."
write-host ("Foobar: "+$foobar)
write-host ("Foobar.Foo : "+$foobar.Foo)

Start-Job -ScriptBlock $ScriptBlock -ArgumentList $foobar | Out-Null
While (Get-Job -State "Running") { Start-Sleep 2 }

write-host ("Jobs Completed.")
Get-Job | Receive-Job
Remove-Job *

输入 XML:

<?xml version="1.0"?>
<Stuff xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<FooBars>
<FooBar>
<Foo>ThisIsAFoo</Foo>
<Bar>ThisIsABar</Bar>
</FooBar>
</FooBars>
</Stuff>

Powershell v2 的输出:

PS C:\Powershell3Issues> .\demo.ps1
Outside the job...
Foobar: System.Xml.XmlElement
Foobar.Foo : ThisIsAFoo
Jobs Completed.
Inside the job...
Foobar : System.Collections.ArrayList System.Collections.ArrayList
Foobar.Foo : ThisIsAFoo

Powershell v3 的输出:

PS C:\Powershell3Issues> .\demo.ps1
Outside the job...
Foobar: System.Xml.XmlElement
Foobar.Foo : ThisIsAFoo
Jobs Completed.
Inside the job...
Foobar : System.Collections.ArrayList System.Collections.ArrayList
Foobar.Foo :

请注意缺少的 Foobar.Foo 值。

我也在 v3 中尝试了 $using 语法,但它做了同样的事情。

最佳答案

尝试指定运行作业的 PowerShell 版本:

Start-Job -ScriptBlock $ScriptBlock -ArgumentList $foobar -PSVersion 2.0

关于powershell - Start-Job 将 XML 对象传递给 -ArgumentList 在 Powershell V2 和 V3 中工作方式不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15578577/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com