【问题标题】:Receive-Job not returning same type as calling the script block without a JobReceive-Job 返回的类型与在没有 Job 的情况下调用脚本块的类型不同
【发布时间】:2017-08-09 18:31:31
【问题描述】:

我正在加载一个在 powershell 脚本中定义某些类型的 F# dll,以便创建一个带有正文的 Web 请求,以将其发送到 F# 中的 Web 服务。其中一种类型如下:

type Resource =
| VM of VMResource
| Unit of UnitResource 

type VMResource = {
    ComputerName: string
    Ip: string
    Attributes: string[]
}

type UnitResource = {
    UnitName: string
    Ip: string
    Username: string
    Password: string
    Attributes: string[]
}

当我运行以下小型 powershell sn-p 时,请求的响应实际上是 GetResourcesResponse 类型(这是一个包含 Resource 数组的记录类型),这就是我想要的:

Add-Type -Path "pathtomydll.dll"

$fullRequestUrl = "http://localhost:2121/Resources/Get"
$body = "{`"Id`":`"Test`",`"RequestedResources`":[{`"ResourceType`":{`"Case`":`"VM`"},`"Attributes`":[`"A1`",`"A2`"]},{`"ResourceType`":{`"Case`":`"Unit`"},`"Attributes`":[]}]}"

$resp = Invoke-WebRequest $fullRequestUrl -Method Post -Body $body -ContentType "application/json"
$obj = [ServerProtocolTypes+GetResourcesResponse]::FromJson($resp)
$obj.GetType() # GetResourcesResponse

不幸的是,当我尝试在 Job 中运行相同的代码时,我得到一个 PSObject 类型,其属性是我的Resource 类型的string 表示的数组(例如:ResourceTypes+Resource+VM),它不包含有关VMResourceUnitResource 的任何信息:

Add-Type -Path "pathtomydll.dll"

$fullRequestUrl = "http://localhost:2121/Resources/Get"
$body = "{`"Id`":`"Test`",`"RequestedResources`":[{`"ResourceType`":{`"Case`":`"VM`"},`"Attributes`":[`"A1`",`"A2`"]},{`"ResourceType`":{`"Case`":`"Unit`"},`"Attributes`":[]}]}"

$job = Start-Job -ScriptBlock { param($url, $reqBody) Add-Type -Path "pathtomydll.dll"; $resp = Invoke-WebRequest $url -Method Post -Body $reqBody -ContentType "application/json"; return [ServerProtocolTypes+GetResourcesResponse]::FromJson($resp) } -ArgumentList ($fullRequestUrl, $body)
Wait-Job $job
$obj = Receive-Job $job
$obj.GetType() # PSObject

在这种情况下,$obj 是一个字符串数组,其中一个条目是 ResourceTypes+Resource+VM,另一个是 ResourceTypes+Resource+Unit

有什么方法可以让我从作业中取回我的GetResourcesResponse 对象,而不是包含string 数组的PSObject

【问题讨论】:

  • 我认为问题在于 Jobs 的输出在返回时会被序列化。您可以使用运行空间而不是作业来运行并行进程并保留本机对象类型。
  • 经过短暂的研究,我发现这确实可能是原因(来自this stackoverflow question)。您可以将其作为答案,并将其选为好的答案。谢谢:)
  • 完成。希望你能解决。 :)

标签: .net powershell parallel-processing f# jobs


【解决方案1】:

根据 cmets:

我认为问题在于 Jobs 的输出在返回时会被序列化。您可以使用运行空间而不是作业来运行并行进程并保留本机对象类型。

【讨论】:

    猜你喜欢
    • 2020-03-29
    • 1970-01-01
    • 2016-08-11
    • 1970-01-01
    • 2016-08-03
    • 2012-09-19
    • 2019-04-13
    • 2021-05-31
    相关资源
    最近更新 更多