gpt4 book ai didi

powershell - 将字符串转换为 PSCustomObject

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

我遇到的问题源于传递了 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

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

最佳答案

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
...

关于powershell - 将字符串转换为 PSCustomObject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44802139/

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