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

前端 未结 10 1897
名媛妹妹
名媛妹妹 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:05

    How about invoking the last command with "r" (alias for Invoke-History) and wrapping it in parentheses() to execute it first?

    Yes this reruns the last command, but in my use cases this is by far the most streamlined solution especially for times when I don't realize that I'll need the last commands output at first.

    It also keeps the object structure intact.

    PS C:\Users\user> Get-NetAdapter -InterfaceIndex 3 | Where {$_.State -match "2"}
    
    Name                      InterfaceDescription                    ifIndex Status       MacAddress             LinkSpeed
    ----                      --------------------                    ------- ------       ----------             ---------
    Ethernet                  Intel(R) Ethernet Connection I217-LM          3 Up           XX-XX-XX-XX-XX-XX       100 Mbps
    
    PS C:\Users\user> (r) |where {$_.LinkSpeed -eq "100 Mbps"}
    Get-NetAdapter -InterfaceIndex 3 | Where {$_.State -match "2"}
    
    Name                      InterfaceDescription                    ifIndex Status       MacAddress             LinkSpeed
    ----                      --------------------                    ------- ------       ----------             ---------
    Ethernet                  Intel(R) Ethernet Connection I217-LM          3 Up           XX-XX-XX-XX-XX-XX       100 Mbps
    
    PS C:\Users\user> (r).MacAddress
    Get-NetAdapter -InterfaceIndex 3 | Where {$_.State -match "2"}
    XX-XX-XX-XX-XX-XX
    

提交回复
热议问题