Powershell Select-Object的-Property参数

时间:2011-07-21 21:05:58

标签: powershell

我对Select-Object cmdlet的一些行为感到困惑。这是一个例子。

PS C:\> $object = get-item C:\windows\Temp
PS C:\> $time = $object.CreationTime
PS C:\> $time.GetType().FullName
System.DateTime
PS C:\> $result = Select-Object -InputObject $object -Property "CreationTime"
PS C:\> $result.GetType().FullName
System.Management.Automation.PSCustomObject
PS C:\>
PS C:\> $result.CreationTime.GetType().FullName
System.DateTime

请注意,CreationTime的类型为System.DateTime但是当我使用Select-Object选择它时,返回的对象的类型为System.Management.Automation.PSCustomObject。它的一些新对象有CreationTime作为其属性。

让我们看一下Select-Object的帮助来解释一下。

  

概要
  选择对象或对象集的指定属性...

这就是我想要的,属性本身......不是属性的一些对象。但如果我们进一步阅读......

  

说明
  ...如果使用Select-Object选择指定的属性,它将从输入对象复制这些属性的值,并创建具有指定属性和复制值的新对象。

我不知道为什么它有用,但它解释了这个对象的返回。

使用-ExpandProperty代替-Property似乎给了财产本身

PS C:\> $result2 = Select-Object -InputObject $object -ExpandProperty "CreationTime"
PS C:\> $result2.GetType().FullName
System.DateTime

为什么-ExpandProperty会这样做?让我们来看看它的帮助:

  

-ExpandProperty
  指定要选择的属性...如果属性包含对象,则该对象的属性将显示在输出中。

在这种情况下,属性是一个对象,我们没有得到“该对象的属性”我们只得到了对象本身。

有人可以告诉我:

  1. 当帮助提到扩展数组并获取属性对象的属性(而不是属性对象本身)时,为什么-ExpandProperty获取属性对象本身?这是我很困惑的地方。我读错了吗?我觉得这需要另一次技术编辑迭代。
  2. 使用“-Property”返回的对象对某些内容有用吗?

2 个答案:

答案 0 :(得分:4)

扩展#1的答案:-expandproperty的最常见用法是将数组属性扩展到数组元素中,尤其是在执行export-csv时。

PS C:\> get-process lsass | select threads | convertto-csv -notype
"Threads"
"System.Diagnostics.ProcessThreadCollection"

不太有用。现在,在该线程集合上使用-expandproperty:

PS C:\> get-process lsass | select -expand threads | convertto-csv -notype

 "BasePriority","CurrentPriority","Id","IdealProcessor","PriorityBoostEnabled","PriorityLevel","PrivilegedProcessorTime"
 ,"StartAddress","StartTime","ThreadState","TotalProcessorTime","UserProcessorTime","WaitReason","ProcessorAffinity","Si
 te","Container"
 "9","10","572",,,,,"2000143616",,"Wait",,,"LpcReceive",,,
 "9","10","588",,,,,"2000143616",,"Wait",,,"UserRequest",,,
 "9","9","592",,,,,"2000143616",,"Wait",,,"UserRequest",,,
 "9","10","596",,,,,"0",,"Wait",,,"EventPairLow",,,
 "9","9","1404",,,,,"0",,"Wait",,,"UserRequest",,,
 "9","9","3896",,,,,"0",,"Wait",,,"EventPairLow",,,
 "9","9","848",,,,,"0",,"Wait",,,"EventPairLow",,,
 "9","11","6216",,,,,"2000143616",,"Wait",,,"UserRequest",,,
 "9","9","7924",,,,,"2000143616",,"Wait",,,"EventPairLow",,,

答案 1 :(得分:3)

Select-object(不带-expandproperty)返回带有您选择的属性集的PSCustomObject。那是因为你可能想要选择多个属性(并且不能期望得到例如2个属性的日期时间对象)。

对#2的回答是,有时候让一个具有较少属性的对象并丢失方法会更好。此外,您可以使用带表达式的select-object返回“计算”属性。

相关问题