Question:
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?
1 2 3 4 5 6 |
PS C:\> Get-ChildItem ... PS C:\> # Oh no, I forgot to assign the output to a variable PS C:\> $a = Get-ChildItem PS C:\> |
Answer:
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:
1 2 3 4 5 |
function out-default { $input | Tee-Object -var global:lastobject | Microsoft.PowerShell.Core\out-default } |
For powershell 5:
1 2 3 4 5 |
function out-default { $input | Tee-Object -var global:lastobject | Microsoft.PowerShell.Utility\out-default } |
And for both:
1 2 3 4 5 6 |
# 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.