无法将 PSObject 作为参数传递给 Start-Process

Unable to pass PSObject as an argument to to Start-Process

我有一个读取输入文件的要求,它是一个 xml(如下所示)

<Parent>
  <Child>
    <grandchilditem1>Server1</grandchilditem1>
    <grandchilditem2>Database1</grandchilditem2>
  </Child>
</Parent>
<Parent>
  <Child>
    <grandchilditem1>Server1</grandchilditem1>
    <grandchilditem2>Database1</grandchilditem2>
  </Child>
</Parent>

我的主要 powershell 脚本解析 xml,并在 foreach 循环中为每个子项创建一个带有输入参数的对象,并使用参数调用另一个 powershell 脚本作为从每个子项创建的对象。这对于 运行 不同控制台中并行的脚本是必要的。

$Child.ChildNodes.GetEnumerator()|ForEach-Object{
  $InputOBJ = New-Object PSObject -Property @{
        Server = $_.grandchilditem1
        Database = $_.grandchilditem2
    }
  $psfilepath = Get-Location
  Start-Process -filepath "powershell.exe" -ArgumentList @("-NoExit", "$psfilepath\ls.ps1 $InputOBJ") -WindowStyle Normal
}

我的问题是,这执行得很好并为 2 个子节点打开了两个不同的控制台,但是 $inputobj 没有完全通过。它得到 t运行 分类。但是,如果我将每个单独的参数作为字符串值传递,它会接受所有参数。

我想知道,对象没有正确通过的原因是什么。

在打开的新控制台中,输出将只是第一项。 例如,我的 ls.ps1 有一个声明

write-host $inputobj 

它输出,就是这个。

@{服务器=服务器1;

对象结构也被破坏了。我相信,它是作为字符串而不是对象发送的。

如果有人对此有更多了解,请告诉我。

因为您只能将字符串传递给 Start-Process an alternative is to serialise the object to xml using Export-Clixml, pass the path to the serialised object, then in your target script deserialise the object using Import-Clixml

您的主脚本将如下所示:

$tempObjectPath = [System.IO.Path]::GetTempFileName()
Export-Clixml -InputObject $InputOBJ -Path $tempObjectPath

$psfilepath = Get-Location
Start-Process `
    -filepath "powershell.exe" `
    -ArgumentList @("-NoExit", "$psfilepath\ls.ps1 $tempObjectPath") `
    -WindowStyle Normal

然后在您的目标脚本中,将 xml 反序列化回您的 PSObject:

$InputOBJ = Import-Clixml -Path $tempObjectPath

# Optionally, delete the temporary file
Remove-Item -Path $tempObjectPath -Force