Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the last object returned

Tags:

powershell

Occasionally I execute a PowerShell command and I forget to store its return values/objects in a variable. Does PowerShell store the returned object of the last command in a variable I could access to?

PS C:\> Get-ChildItem 
... 
PS C:\> # Oh no, I forgot to assign the output to a variable
PS C:\> $a = Get-ChildItem
PS C:\> 
like image 876
Martin Avatar asked Nov 14 '14 18:11

Martin


2 Answers

From stuffing the output of the last command into an automatic variable: override out-default and store the results in a global variable called $lastobject.

For powershell 6 and newer:

function out-default {
  $input | Tee-Object -var global:lastobject | 
  Microsoft.PowerShell.Core\out-default
}

For powershell 5:

function out-default {
  $input | Tee-Object -var global:lastobject | 
  Microsoft.PowerShell.Utility\out-default
}

And for both:

# In case you are using custom formatting
# You will need to override the format-* cmdlets and then
# add this to your prompt function

if($LastFormat){$LastOut=$LastFormat; $LastFormat=$Null }

Solution posted by Andy Schneider and inspired by comments from "//\o//" and Joel.

like image 156
Tanner.R Avatar answered Nov 03 '22 02:11

Tanner.R


Currently on WMF 5.1, it looks like Out-Default is in a different namespace.

function Out-Default {
    $Input | Tee-Object -Var Global:LastOutput |
        Microsoft.PowerShell.Core\Out-Default
}
like image 40
Jeremy Fortune Avatar answered Nov 03 '22 01:11

Jeremy Fortune