为 Select-Object 或 Format-Table 使用变量

Use Variable for Select-Object or Format-Table

我有一个类似的问题:Question 44460843

我想为字段使用变量。

这个例子运行良好:

$x = ("Id,ProcessName,CPU").split(",")
Get-Process | ft -a $x

但是,如果我想要这样的自定义字段,我该如何获取它?

Get-Process | ft -a Id,ProcessName,@{Name = 'CPUx' ; Expression = {$_.CPU}}

我试过了,但没用:

$x = ("Id,ProcessName,@{Name = 'CPUx' ; Expression = {$_.CPU}}").split(",")
Get-Process | ft -a $x

有人知道怎么做吗? 我是一个懒惰的人,想避免这种 copy/paste 长文本狂欢。

注:

  • 答案类似于 Select-Object cmdlet,它应该用于提取属性以供以后 程序化处理
    Format-* cmdlet,如 Format-Table in this case (whose built-in alias is ft), are only intended to produce for-display formatting; see this answer 了解更多信息。

Theo已在评论中提供解决方案:

$x = 'Id', 'ProcessName', @{ Name = 'CPUx' ; Expression = { $_.CPU } }
Get-Process | Format-Table -AutoSize $x  # same as: ft -a $x

也就是说,链接问题的 the answer 也适用于您的情况,即使它恰好仅使用 文字字符串 作为 属性 名称:

直接构造一个属性个名字和calculated properties, using ,, the array constructor operator的数组,它允许你使用任何文字和变量的混合;例如:

$pName = 'processName'                               # property name
$pCpu = @{ Name = 'CPUx' ; Expression = { $_.CPU } } # calculated property

$x = 'Id', $pName, $pCpu

不要单个字符串开始,你用.Split()分割成一个标记数组,因为它会将您限制为 属性 names,因为标记总是 strings.


顺便说一句:

数组将位置绑定到Format-Table的(ft的)-Property参数,你可以很容易地发现作为以及 array of 属性 names / calculated properties 被发现的事实如下:

PS> Format-Table -?
...

SYNTAX
    Format-Table [[-Property] <System.Object[]>] ...

DESCRIPTION
...
  • 外面的[...]告诉你这个参数整体是可选的

  • -Property 周围的 [...] 告诉您显式指定参数名称是可选的,即支持 positional 绑定。

  • <System.Object[]> 告诉您 System.Object 个实例的数组 ([]) 应该作为参数的类型。

要获取有关可能传递哪些对象的更多信息,请分别检查参数:

PS> Get-Help Format-Table -Parameter Property

-Property <System.Object[]>
    Specifies the object properties that appear in the display and the order 
    in which they appear. Type one or more property names, separated 
    by commas, or use a hash table to display a calculated property. 
    Wildcards are permitted.
...