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:\>
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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With