Martin
Martin

Reputation: 40583

Get the last object returned

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:\> 

Upvotes: 9

Views: 2382

Answers (2)

Tanner.R
Tanner.R

Reputation: 479

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.

Upvotes: 8

Jeremy Fortune
Jeremy Fortune

Reputation: 2499

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
}

Upvotes: 2

Related Questions