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

前端 未结 10 2060
名媛妹妹
名媛妹妹 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 01:20

    This is from Windows Powershell in Action. Source this in your $profile, and it makes $last contain the output of the last command. It also will change directories by typing the name of the directory a la zsh, or go to a website in a browser by typing the url of the website. It makes an Out-Default function that overrides the Out-Default cmdlet and calls it. I added the "start-process $__command" line so going to a website would work in osx.

    This is fairly invasive. I later disabled it in my $profile for some reason.

    #
    # Wrapping an exiting command with a function that uses
    # steppable pipelines to "remote-control" the wrapped command.
        
    function Out-Default
    {
      [CmdletBinding(ConfirmImpact="Medium")]
      param(
        [Parameter(ValueFromPipeline=$true)] 
        [System.Management.Automation.PSObject] $InputObject
      )
        
      begin {
        $wrappedCmdlet = $ExecutionContext.InvokeCommand.GetCmdlet(
          "Out-Default")
        $sb = { & $wrappedCmdlet @PSBoundParameters }
        $__sp = $sb.GetSteppablePipeline()
        $__sp.Begin($pscmdlet)
      }
    
      process {
        $do_process = $true
        if ($_ -is [System.Management.Automation.ErrorRecord]) {
          if ($_.Exception -is 
          [System.Management.Automation.CommandNotFoundException]) {
            $__command = $_.Exception.CommandName
            if (test-path -path $__command -pathtype container) {
              set-location $__command
              $do_process = $false
            }
            elseif ($__command -match '^http://|\.(com|org|net|edu)$') {
              if ($matches[0] -ne "http://") {$__command = "HTTP://" + 
                $__command }
              # [diagnostics.process]::Start($__command)
              start-process $__command
              $do_process = $false
            } 
          } 
        }
        if ($do_process) {
          $global:LAST = $_;
          $__sp.Process($_)
        }  
      }
    
      end {
        $__sp.End()
      }
    
    }
    

提交回复
热议问题