为什么Powershell的Format-List *不输出所有属性

时间:2017-11-14 11:51:58

标签: powershell

当我... | Format-List时,其中一个属性为Path 当我执行... | Format-List *时,Path属性丢失 为什么呢?

[DBG]: PS C:\Directory>> $MyInvocation.MyCommand | Format-List

Name        : 
CommandType : Script
Definition  : $MyInvocation.MyCommand | Format-List
Path        : 

[DBG]: PS C:\Directory>> $MyInvocation.MyCommand | Format-List *

HelpUri            : 
ScriptBlock        : $MyInvocation.MyCommand | Format-List *
Definition         : $MyInvocation.MyCommand | Format-List *
OutputType         : {}
Name               : 
CommandType        : Script
Visibility         : Public
ModuleName         : 
Module             : 
RemotingCapability : PowerShell
Parameters         : 
ParameterSets      : {}

2 个答案:

答案 0 :(得分:4)

赞美gms0ulman's answer ...

PowerShell根据format.ps1xml文件显示控制台对象。来自Formatting File Overview

  

命令(cmdlet,函数和脚本)返回的对象的显示格式是使用格式化文件(format.ps1xml文件)定义的。 Windows PowerShell提供了其中一些文件来定义Windows PowerShell提供的命令返回的那些对象的显示格式...

PowerShell,在被指示时,有一种特殊的方式来显示对象,除非另有说明。在您的情况下,这来自文件PowerShellCore.format.ps1xml。通过检查$MyInvocation.MyCommand的类型,我们知道它是System.Management.Automation.ScriptInfo对象。知道我们可以从上面的文件中提取格式细节。

<View>
    <Name>System.Management.Automation.ScriptInfo</Name>
    <ViewSelectedBy>
        <TypeName>System.Management.Automation.ScriptInfo</TypeName>
    </ViewSelectedBy>


    <ListControl>
        <ListEntries>
            <ListEntry>
               <ListItems>
                    <ListItem>
                        <PropertyName>Name</PropertyName>
                    </ListItem>
                    <ListItem>
                        <PropertyName>CommandType</PropertyName>
                    </ListItem>
                    <ListItem>
                        <PropertyName>Definition</PropertyName>
                    </ListItem>
                    <ListItem>
                        <PropertyName>Path</PropertyName>
                    </ListItem>
                </ListItems>
            </ListEntry>
        </ListEntries>
    </ListControl>
</View>

所以我们看到它会尝试显示Name,CommandType,Definition和 Path 。如您所知,为所有属性指定*将显示对象 1

的所有当前属性

Path is null of course because of where you ran it from.

1 该语句的一个小异常,因为某些常见的对象属性被隐藏到*。在这种情况下,使用-Force显示所有内容。无论你知道他们的名字,都可以访问它们。

答案 1 :(得分:3)

在控制台中运行时,Path属性实际上不存在。 Format-List - 没有* - 正在使用模板来确定要显示的属性。 不幸的是我找不到文档链接来进一步解释这个,以及如何配置它 - 如果我这样做就会编辑。
See Matt's answer

您可以通过运行$MyInvocation.MyCommand | Get-Member并注意Path不是其中一个属性来查看此内容。这是有道理的,因为您在控制台中运行命令,而不是从脚本运行。

在脚本中,$MyInvocation.MyCommand | Format-List$MyInvocation.MyCommand | Format-List *都包含Path

  

仅为脚本,函数和脚本块填充$ MyInvocation。

来自about_Automatic_Variables。看起来PowerShell将您的命令视为脚本,以便(部分)填充$MyInvocation

相关问题