我需要读取一个输入文件,它是一个 xml(如下所示)
<Parent>
<Child>
<grandchilditem1>Server1</grandchilditem1>
<grandchilditem2>Database1</grandchilditem2>
</Child>
</Parent>
<Parent>
<Child>
<grandchilditem1>Server1</grandchilditem1>
<grandchilditem2>Database1</grandchilditem2>
</Child>
</Parent>
我的主要 powershell 脚本解析 xml,并在 foreach 循环中为每个 Child 创建一个带有输入参数的对象,并使用从每个子项创建的对象的参数调用另一个 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 没有完全通过。它被截断。但是,如果我将每个单独的参数作为字符串值传递,它会接受所有参数。
我想知道,对象没有正确传递的原因是什么。
在打开的新控制台中,输出将只是第一项。例如,我的 ls.ps1 有一个声明
write-host $inputobj
它输出,就是这个。
@{服务器=服务器1;
对象结构也受到损害。我相信,它是作为字符串而不是对象发送的。
如果有人对此有更多了解,请告诉我。
由于您只能将字符串传递给Start-Process,因此另一种方法是使用Export-Clixml将对象序列化为xml ,将路径传递给序列化对象,然后在目标脚本中使用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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句