使用Powershell脚本仅显示别名名称列 [英] Use Powershell script to display just alias name column

查看:101
本文介绍了使用Powershell脚本仅显示别名名称列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

经过多年的unix/linux脚本编写,我对Powershell脚本编写还很陌生,但我仍在尝试获取对象输出的句柄.我正在尝试运行Get-Alias命令以仅返回名称"列.当我尝试仅选择名称"列时,我要么得到整个get-alias输出,要么出错. 我尝试使用的脚本/命令行是:get-alias | format-table

I'm fairly new to powershell scripting after years of unix/linux scripting and I'm still trying to get the handle of object output. I am trying to run the Get-Alias command to return just the column "Name." When I try to select just the column "name" I either get the whole get-alias output, or errors. The script/ command line I am trying to use is: get-alias | format-table

当我添加select-object逻辑时,它要么切断别名的名称,要么保留命令名称,否则select-object逻辑将被忽略.我敢肯定解决方案很简单.谢谢

When I add select-object logic, it either cuts off the name of the alias and leaves off the command name or the select-object logic is just ignored. I'm sure the solution is simple. Thanks

推荐答案

tl; dr :

PS> Get-Alias | Select-Object -ExpandProperty DisplayName

? -> Where-Object                                                                                              
cd -> Set-Location 
...

也就是说,Name 显示列之下的真实属性名称是DisplayName.

That is, the true property name underlying the Name display column is DisplayName.

PowerShell的默认输出格式有时使用的列名称与基础对象的属性名称不同(在这种情况下)和/或使用计算的.

PowerShell's default output formatting sometimes uses column names that differ from or the underlying objects' property names (which is the case here) and/or use values that are calculated.

默认情况下显示为列Name的实际上是基础对象的.DisplayName属性,而真正的.Name属性仅包含别名自己的名称.

What shows as column Name by default is actually the underlying objects' .DisplayName property, whereas the true .Name property contains just the alias' own name.

您可以通过Get-Member检查对象类型的成员(属性和方法),或者查看给定对象的属性(而不是方法)名称及其具体的,输送到Format-List *:

You can inspect the members (properties and methods) of an object's type via Get-Member or, to see both the property (but not method) names and their concrete values for a given object, pipe to Format-List *:

PS> Get-Alias | Select-Object -First 1 | Format-List *

HelpUri             : https://go.microsoft.com/fwlink/?LinkID=113423
ResolvedCommandName : Where-Object
DisplayName         : ? -> Where-Object
ReferencedCommand   : Where-Object
ResolvedCommand     : Where-Object
Definition          : Where-Object
Options             : ReadOnly, AllScope
Description         : 
OutputType          : {}
Name                : ?
CommandType         : Alias
Source              : 
Version             : 
Visibility          : Public
ModuleName          : 
Module              : 
RemotingCapability  : None
Parameters          : {[InputObject, System.Management.Automation.ParameterMetadata], [FilterScript, System.Management.Automation.ParameterMetadata], [Property, 
                      System.Management.Automation.ParameterMetadata], [Value, System.Management.Automation.ParameterMetadata]...}
ParameterSets       : 


可选阅读:如何检查给定类型的格式数据:

有关背景信息,请参见


Optional reading: How to inspect a given type's formatting data:

For background information, see Get-Help about_Format.ps1xml.

Get-Alias输出[System.Management.Automation.AliasInfo]实例(Get-Member会告诉您).

Get-Alias outputs [System.Management.Automation.AliasInfo] instances (as Get-Member will tell you).

使用Get-FormatData cmdlet,您可以检查类型的格式数据:

Using the Get-FormatData cmdlet you can inspect a type's formatting data:

注意事项:出于向后兼容的原因,默认情况下并非所有有效格式数据都由Get-FormatData报告-请参阅

Caveat: Not all formatting data in effect is by default reported by Get-FormatData for backward-compatibility reasons - see this GitHub issue; notable omissions are [System.IO.FileInfo] and [System.IO.DirectoryInfo], as returned by Get-ChildItem / Get-Item ; in short, to see all formatting data in effect for the PowerShell version at hand, use:

Get-FormatData -PowerShellVersion $PSVersionTable.PSVersion [...]

具有讽刺意味的是,没有为Get-Format输出的System.Management.Automation.ExtendedTypeDefinition实例定义自定义格式数据,默认格式无济于事.

Somewhat ironically, there is no custom formatting data defined for the System.Management.Automation.ExtendedTypeDefinition instances that Get-Format outputs, and the default formatting isn't helpful.

当前,检查格式数据的最简单方法是通过管道连接到Format-Custom cmdlet ,该cmdlet提供了一种非正式的,易于理解的对象内部结构表示形式:

Currently, the simplest way to inspect formatting data is to pipe to the Format-Custom cmdlet, which provides an informal, human-readable representation of the internal structure of objects:

# Best to send this to a file and open that file in a text editor for perusal.
$prev, $FormatEnumerationLimit = $FormatEnumerationLimit, [int]::MaxValue
Get-FormatData System.Management.Automation.AliasInfo | Format-Custom -Depth 10
$FormatEnumerationLimit = $prev

注意:

  • $FormatEnumerationLimit暂时设置为最大可能值,以确保在输出中显示所有列/属性定义(默认情况下,最多只能显示 4 ,并用...(Windows PowerShell,3个字符)/(PowerShell Core,1个字符)指示省略的字符.

  • $FormatEnumerationLimit is temporarily set to the highest possible value to ensure that all column / property definitions are shown in the output (by default, only up to 4 would be shown, and omitted ones would be indicated with ... (Windows PowerShell, 3 chars.) / (PowerShell Core, 1 char.).

-Depth 10确保输出对象的内部结构得到完整表示;默认情况下,最多只能达到 5 个级别.

-Depth 10 ensures that the internal structure of the output objects is fully represented; by default, only up to 5 levels would be.

输出将像JSON一样模糊地显示 ,并且仅适用于视觉检查,不适用于程序处理.

The output will look vaguely like JSON, and is suited to visual inspection only, not programmatic processing.

您将看到以下一个或多个块:

You'll see one or more of the following blocks:

class ExtendedTypeDefinition
{
  TypeNames = 
    [
      <typeName>
    ]

  FormatViewDefinition = 
    [
      class FormatViewDefinition
      {
        Name = <formatName>
        Control = 
          class <viewType>Control
        ...
      }
      class FormatViewDefinition
      {
        Name = <formatName>
        Control = 
          class <viewType>Control
        ...
      }
}

  • <typeName>是格式适用的完整类型名称(例如System.Management.Automation.AliasInfo)

    • <typeName> is the full type name to which the format applies (e.g., System.Management.Automation.AliasInfo)

      <formatName>是内部使用的非标准化名称,用于手头的格式定义

      <formatName> is an internally used, non-standardized name for the format-definition at hand

      <viewType>Control是以下类之一,用于定义与相应的Format-Table, Format-List,Format-WideFormat-Custom cmdlet一起使用的视图:TableControlListControlWideControlCustomControl,均源自 System.Management.Automation.PSControl基类.

      <viewType>Control is one of the following classes, defining the views for use with the corresponding Format-Table,Format-List, Format-Wide, and Format-Custom cmdlets: TableControl, ListControl, WideControl, CustomControl, all derived from the System.Management.Automation.PSControl base class.

      请注意,输出可能包含重复信息,就像System.Management.Automation.AliasInfo一样(因为对于共享的所有 other 命令类型重复格式信息相同的格式),但是检查感兴趣的 first class <viewType>Control实例就足够了.

      Note that the output may contain duplicate information, as it does in the case of System.Management.Automation.AliasInfo (because the formatting information is repeated for all other command types that share the same formatting), but it is sufficient to examine the first class <viewType>Control instance of interest.

      具体来说,这是第一个class TableControl块的摘录:

      Specifically, here's an excerpt from the first class TableControl block:

      class TableControl   # Defines the format for Format-Table
      {
        Headers =   # The table headers (column names and column properties)
            ...
            class TableControlColumnHeader # The "Name" column *header*
            {
              Label = Name
              Alignment = Undefined
              Width = 50
            }
            ...
          ]
      
        Rows =  # The table rows (underlying or calculated property values)
          [
            class TableControlRow
            {
              Columns = 
                [
                  ...
                  class TableControlColumn  # The "Name" column *value*
                  {
                    Alignment = Undefined
                    DisplayEntry = 
                      class DisplayEntry
                      {
                        ValueType = ScriptBlock  #  A *calculated* property 
                        Value = 
                                                        if ($_.CommandType -eq "Alias")
                                                        {
                                                          $_.DisplayName
                                                        }
                                                        else
                                                        {
                                                          $_.Name
                                                        }
      
                      }
                    FormatString = 
                  }
                  ...
          ]
          ...
      
      

      请注意,标题和列值定义在位置上匹配.例如,第二个TableControlColumn实例定义第二个TableControlColumnHeader实例的值.

      Note that the header and column-value definitions are matched positionally; e.g., the 2nd TableControlColumn instance defines the value for the 2nd TableControlColumnHeader instance.

      上面的内容解释了为什么即使该列标题为名称",它还是显示为别名的".DisplayName"属性,而所有其他命令类型均通过其".Name"属性来表示.嵌入式 script 块(其中的$_代表手边的输入对象的那段PowerShell代码).

      The above explains why, even though the column is entitled "Name", it is an alias' .DisplayName property that is displayed, whereas all the other command types are represented by their .Name property, by way of the embedded script block (the piece of PowerShell code in which $_ represents the input object at hand).

      默认情况下,决定为别名显示.DisplayName是为了提供更多有用的信息,但是列名和基础属性名之间的差异肯定会导致混淆.

      Presumably, the decision to show the .DisplayName for aliases was made to provide more helpful information by default, but the discrepancy between the column name and underlying property name can certainly lead to confusion.

      请注意,对于类型[System.Management.Automation.AliasInfo],还存在一个 dedicated 表视图,该视图(a)仅定义2列,并且(b)用其真实名称调用.DisplayProperty列值. br> 但是,从上面列出的PowerShell版本开始,该视图被上述的多类型定义抢占了 ,并且实际上被忽略了.

      Note that there is also a dedicated table view for type [System.Management.Automation.AliasInfo] that (a) defines only 2 columns, and (b) calls the .DisplayProperty column values by their true name.
      However, as of the PowerShell versions listed above, this view is preempted by the multi-type definition discussed above and effectively ignored.

      这篇关于使用Powershell脚本仅显示别名名称列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆