有时我执行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)
从将最后一个命令的输出填充到一个自动变量中:覆盖默认值,并将结果存储在一个名为$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的评论的启发。
| 归档时间: |
|
| 查看次数: |
861 次 |
| 最近记录: |