将字符串转换为PSCustomObject

时间:2017-06-28 12:15:26

标签: powershell casting start-process

我遇到的问题源于将PSCustomObject作为参数传递给Start-Process cmdlet(我实际上是在启动一个新的PowerShell进程,以便从调用脚本异步运行脚本)。虽然参数定义为类型PSCustomObject,但由于某种原因它被接受为字符串,因此看起来我需要将其转换回PSCustomObject以访问任何属性。

以下是我的调用脚本的必要部分:

# Convert JSON object to PowerShell object
$payload = ConvertFrom-Json $body

Write-Host $payload
## Returns exactly the following PsCustomObject:

## @{os=Windows Server Datacenter 2016; vmName=sbtestvm; diskType=Managed; username=testuser;
## password=Pa55w.rd1234; location=West Europe; size=Standard_D1;
## requestType=0; sender=test}

Write-Host $payload.os
## Returns: Windows Server Datacenter 2016

# Fire up new worker shell asynchronously
Start-Process powershell.exe -ArgumentList '-NoExit', "$PSScriptRoot\ServiceBus-AsyncWorker.ps1", "'$payload'"  # -Windowstyle Hidden

我执行的脚本:

Param(
    [Parameter(Mandatory=$True)]
    [PSCustomObject]$Request
)

# Import RequestHandler module to deal with processing service bus requests
Import-Module $PSScriptRoot\RequestHandler\RequestHandler.psm1

Write-Host $Request
## Returns exactly the same as 'Write-Host $payload' in the calling script

Write-Host $Request.os
## Returns empty string

Write-Host $Request.GetType()
## Returns System.String <--- This is the issue

长话短说:有没有办法防止这个对象首先被自动解析为字符串?如果不是 - 如何将此字符串强制转换回相关的对象类型?

1 个答案:

答案 0 :(得分:2)

Start-Process powershell.exe启动新的PowerShell流程。您无法跨进程边界传递PowerShell对象。

你可以改变

Start-Process powershell.exe -ArgumentList '-NoExit', "$PSScriptRoot\ServiceBus-AsyncWorker.ps1", "'$payload'"

$PSScriptRoot\ServiceBus-AsyncWorker.ps1 $payload

以避免创建新进程,但这将在同一窗口中运行脚本。

如果您需要运行从控制台分离的脚本,您可以将其作为background job运行:

$job = Start-Job -ScriptBlock {
    Param($Path, $Data)
    & "$Path\ServiceBus-AsyncWorker.ps1" $Data
} -ArgumentList $PSScriptRoot, $payload

否则,您需要在生成新进程时以序列化形式(例如原始JSON)传递参数:

Start-Process powershell.exe -ArgumentList '-NoExit', "$PSScriptRoot\ServiceBus-AsyncWorker.ps1", "`"$body`""

然后(重新)从字符串中创建对象:

Param(
    [Parameter(Mandatory=$true)]
    [string]$Json
)

# Import RequestHandler module to deal with processing service bus requests
Import-Module $PSScriptRoot\RequestHandler\RequestHandler.psm1

$Request = ConvertFrom-Json $Json
...