【问题标题】:Get the last object returned获取最后返回的对象
【发布时间】:2014-11-14 18:12:57
【问题描述】:

有时我执行了一个 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:\> 

【问题讨论】:

  • 这对于交互式 PowerShell 来说是一个很棒的功能。我发现类似的 Python 交互变量 _ 非常有用。 “在 [Python] 交互模式下,最后打印的表达式被分配给变量 _。” 来自 Informal Introduction to Python - 搜索页面“最后打印的表达式”

标签: powershell


【解决方案1】:

来自stuffing the output of the last command into an automatic variable:覆盖out-default 并将结果存储在名为$lastobject 的全局变量中。

对于 powershell 6 及更高版本:

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

对于 powershell 5:

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

对于两者:

# 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 }

解决方案由 Andy Schneider 发布,灵感来自 "//\o//" 和 Joel 的 cmets。

【讨论】:

  • 其实Tanner,我认为这是对用户问题的一个很好的解决方案。不过,不鼓励仅链接的答案。不过,您应该复制实际功能并对其进行简要说明,因为链接可能会断开。
  • 确实很有趣,它会损害性能,但对于开发环境,我会说这是对所提供功能的公平权衡
【解决方案2】:

目前在 WMF 5.1 上,Out-Default 似乎位于不同的命名空间中。

function Out-Default {
    $Input | Tee-Object -Var Global:LastOutput |
        Microsoft.PowerShell.Core\Out-Default
}

【讨论】:

  • 这作为评论会更好 - 但是我已经更新了主要答案以包含一个较新的 Powershell 的示例。
猜你喜欢
  • 2016-04-08
  • 2016-10-14
  • 1970-01-01
  • 2020-01-27
  • 2017-03-26
  • 2021-07-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多