获取返回的最后一个对象

Mar*_*tin 4 powershell

有时我执行PowerShell命令,但忘记将其返回值/对象存储在变量中。PowerShell是否将最后一个命令的返回对象存储在我可以访问的变量中?

PS C:\> Get-ChildItem 
... 
PS C:\> # Oh no, I forgot to assign the output to a variable
PS C:\> $a = Get-ChildItem
PS C:\> 
Run Code Online (Sandbox Code Playgroud)

Tan*_*r.R 6

将最后一个命令的输出填充到一个自动变量中:覆盖默认值,并将结果存储在一个名为$lastobject

对于Powershell 6和更高版本:

function out-default {
  $input | Tee-Object -var global:lastobject | 
  Microsoft.PowerShell.Core\out-default
}
Run Code Online (Sandbox Code Playgroud)

对于Powershell 5:

function out-default {
  $input | Tee-Object -var global:lastobject | 
  Microsoft.PowerShell.Utility\out-default
}
Run Code Online (Sandbox Code Playgroud)

对于两者:

# 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 }
Run Code Online (Sandbox Code Playgroud)

解决方案由Andy Schneider发布,并受到“ // \ o //”和Joel的评论的启发。

  • 实际上,坦纳,我认为这是解决用户问题的绝佳解决方案。但是不鼓励仅链接的答案。您应该已经复制了实际功能和简要说明,因为链接可能会断开。 (4认同)