在其中运行Scriptblock';s自己的实例并将ExitCode返回到PowerShell中的父脚本
我正在尝试将PowerShell脚本作为XML文件中的节点,该文件返回的退出代码为1或0。然后,我希望在与父PS脚本分离的实例中运行此脚本,但将其退出代码返回给父实例,以便我可以基于ExitCode编写If语句 现在,我简化了XML PowerShell脚本(这似乎工作正常,没有任何问题): 以下是我在父PS脚本中的代码:在其中运行Scriptblock';s自己的实例并将ExitCode返回到PowerShell中的父脚本,powershell,Powershell,我正在尝试将PowerShell脚本作为XML文件中的节点,该文件返回的退出代码为1或0。然后,我希望在与父PS脚本分离的实例中运行此脚本,但将其退出代码返回给父实例,以便我可以基于ExitCode编写If语句 现在,我简化了XML PowerShell脚本(这似乎工作正常,没有任何问题): 以下是我在父PS脚本中的代码: #write XML script to string then convert string to scriptblock [String]$installCheck_Sc
#write XML script to string then convert string to scriptblock
[String]$installCheck_ScriptString = $package.installcheck_script
$installCheck_Script = [Scriptblock]::Create($installCheck_ScriptString)
#start new instance of powershell and run script from XML
$process = (Start-Process powershell.exe -ArgumentList "-command {$installCheck_Script} -PassThru -Wait")
$installCheck_ScriptResult = $process.ExitCode
If ($installCheck_ScriptResult -gt 0)
{
....
}
在处理代码时,我似乎收到了一条消息,其中Wait或Passthru是意外的标记,或者我没有得到任何ExitCode值
$LastExitCode
始终返回一个0。-Wait
和-PASSTRU
对于powershell.exe
是无效的参数。您的意思是像这样将它们应用于启动流程
$process = (Start-Process powershell.exe -ArgumentList "-command {$installCheck_Script}" -PassThru -Wait)
请注意,这种方法会有一些问题。如果$installCheck\u Script
包含任何需要转义的字符,您将进行大量检查和替换
通过将-EncodedCommand
与powershell.exe一起使用,并传入脚本的base64编码版本,可以避免这种情况:
$encodedScript = [Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes($installCheck_Script))
$process = (Start-Process powershell.exe -ArgumentList "-EncodedCommand",$encodedScript -PassThru -Wait)
但只有当你坚持要通过shell打电话时才这样做
更好的(?)方法:
作为你正在做的选择(剥壳),你可以考虑创建一个作业,然后使用一个实际的返回值:< /P>而不是使用退出代码。
$installCheck_Script = " 1 " # for example
$sb = [ScriptBlock]::Create($installCheck_Script)
$job = Start-Job -ScriptBlock $sb
$job | Wait-Job
$code = $job | Receive-Job
如果您想要更好的性能,可以在运行空间的过程中实现。使用它可以更轻松地使用运行空间,使用方式和使用作业类似
$installCheck_Script = " 1 " # for example
$sb = [ScriptBlock]::Create($installCheck_Script)
$job = Start-Job -ScriptBlock $sb
$job | Wait-Job
$code = $job | Receive-Job