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

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

    For my specific use case, I was running a batch file from PowerShell, and I wanted to print the output of that batch file in real-time AND save the output into a variable. I was able to accomplish this by piping the output of my call operator to Tee-Object:

    $args = @('-r', '-a');
    & "C:\myFile.bat" $args | Tee-Object -Variable output;
    $output | Set-Clipboard;
    

    The first command sets up my arguments for the batch file. The second command runs the batch file using the call operator with my arguments, and it pipes the output to the Tee-Object command, which prints the output in real-time from the call operator, but also saves all the information into a new variable called output. The last command simply copies the contents of $output to the clipboard.

    Tee-Object also allows saving output to a file (Unicode encoding), and if I need to save to a file and a variable (in addition to printing to the console), I can chain multiple calls to Tee-Object together in one pipeline. See this link for more information:

    https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/tee-object

提交回复
热议问题