获取进程的退出代码不是由powershell启动的(从get-process cmdlet退出代码)

时间:2016-09-26 15:28:48

标签: windows powershell install silent

公平警告,我是一个PowerShell n00b,这是我的第一个剧本,但是经过2天的研究后我没能找到答案(也许我缺乏正确的术语?)所以我保证给专家!

在执行PW脚本来控制应用程序的静默安装时,我有两个要监视的进程:第一个做出某些决定的setup.exe并根据结果启动2个独立的setup.exe。我的脚本必须启动第一个setup.exe,让它做它的事情,然后获取两个setup.exe的退出代码,虽然我没有问题得到第一个的退出代码,我找不到如何为第二个做同样的事。

我的脚本如下所示:

$LogFile = [PathToMyLog]\MyLog.log
$SetupPath = c:\Users\[MyUsername]\Desktop\Setup.exe


#This part runs the first setup and gets the exit code.

$FirstSetup = Start-Process -filepath $SetupPath -passthru
$SetupID = $FirstSetup.id
wait-process -id $SetupID
$FirstExitCode = FirstSetup.exitCode
add-content  $LogFile "Return Code for the first setup is: $FirstExitCode"

#This second part gets the other setup.exe process and tries to find its
exit code

If ($ExitCode -eq 0 -or -eq 3010)
{
    Do
    {
        Start-Sleep -seconds 2
        $SecondSetup = Get-Process -name Setup -ErrorAction SilentlyContinue
        $SecondSetupID = $SecondSetup.id
    }
    Until ($SetupID -ne $SecondSetupID -and -$SecondSetupID -ne $null)

    Wait-Process -inputobject $SecondSetup
    $SecondExitCode = $SecondSetup.ExitCode
    add-content  $LogFile "Return Code for the Second setup is: $SecondExitCode"
    If ($SecondExitCode -eq 0 -or -eq 3010)
    {
        add-content  $LogFile "Install completed successfully"
    }
    Else
    {
        add-content  $LogFile "Install failed at the second Setup.exe stage"
        Exit $SecondExitCode
    }
}
else
{
add-content  $LogFile "Install failed at the first Setup.exe stage"
Exit $FirstExitCode

执行后,我的$SecondExitCode变量始终为空(因此if块会通过“在第二个setup.exe阶段安装失败”路径。

进行更简单的测试(例如尝试获取notepad.exe进程退出代码),如果我使用start-process 脚本中启动notepad.exe,我可以关闭它时总是得到退出代码,但是如果我手动启动记事本然后使用Get-process cmdlet,我会得到一个包含ID,路径和所有好东西的流程对象,除了退出代码。

我尝试使用waitforExit()代替(之后使用Write-Verbose $process.exitCode行),但它出错了:

>     Write-Verbose : Cannot bind argument to parameter 'Message' because it is null.
>     At line:7 char:15
>     + Write-Verbose $notepad.exitcode
>     +               ~~~~~~~~~~~~~~~~~
>         + CategoryInfo          : InvalidData: (:) [Write-Verbose], ParameterBindingValidationException
>         + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.WriteVerboseCommand

为什么会这样?我认为所有过程对象都是平等的,无论是谁开始它们。那我怎么能得到第二个setup.exe的这个讨厌的退出代码?

P.S。我正在运行PW 4.0

先谢谢大家!

1 个答案:

答案 0 :(得分:0)

具有讽刺意味的是,一旦我允许有足够的时间运行Windows更新,它就会自动开始工作(我正在处理一个不断恢复到基本映像快照的虚拟机)。让它过夜并重新启动后,我得到了#34;等待更新正在安装"窗口,之后我的get-process流程对象能够毫无问题地看到.ExitCode属性。

这是意料之外的,但有道理。