PowerShell: Is there an automatic variable for the last execution result?

前端 未结 10 1874
名媛妹妹
名媛妹妹 2021-02-05 00:29

I\'m looking for a feature comparable to Python interactive shell\'s \"_\" variable. In PowerShell I want something like this:

> Get-Something # this returns          


        
10条回答
  •  借酒劲吻你
    2021-02-05 00:55

    An approach that has worked for me is to process the command's output with Select-Object as a pass-through. For instance, I had a console EXE that output verbose output to stderr and meaningful output to stdout, of which I wanted to capture only the last line.

    $UtilityPath = ""
    
    (UpdateUtility.exe $ArgList 2>&1) | % {
        If ($_ -Is [System.Management.Automation.ErrorRecord]) {
            $_.Exception.Message
        }
        Else {
            $_
            $UtilityPath = $_
        }
    }
    

    The way this script was being invoked, having output on PowerShell's Error output stream was considered a hard error, which didn't mesh nicely with the way PowerShell takes external apps' stderr output and turns it into Error output. This approach of wrapping the output allowed me to control how it passed through, as well as capture the stdout line I wanted. It seems to me that this would be a fairly flexible approach that would allow you to intercept output and do anything you want with it as it passes through. For instance:

    $CommandOutput = ""
    
    SomeOtherCommand | % {
        $CommandOutput += "$_`r`n"
        $_
    }
    

提交回复
热议问题