PowerShell -ExpandProperty 和正确的日期格式

PowerShell -ExpandProperty and correct date format

我正在尝试使用 PowerShell 中的 -ExpandProperty 功能来阻止 header 出现在输出中并格式化没有分钟和秒的日期。这只是为了获取 AD Object:

的创建日期
Get-ADComputer -Server $Server -Identity BlahBlah -Properties Created |
  Select-Object -ExpandProperty @{Name="Created";Expression={$_.Created.ToString("yyyy-MM-dd")}} 

这不会产生结果,只有当我排除 "-ExpandProperty" 部分时,它才会产生正确的日期格式,但包括我不想要的 header "Created"

有什么想法吗?

我目前无法访问广告,但这可能是您想要的

已更新

Get-ADComputer -Server $Server -Identity BlahBlah -Properties Created | Select-Object Created | ForEach-Object {$_.Created.ToString("yyyy-MM-dd")}

在 PowerShell 中几乎总是有不止一种解决问题的方法-

(Get-ADComputer -Server $Server -Identity BlahBlah -Properties Created | 
  Select-Object @{N="Created";E{$_.Created.ToString("yyyy-MM-dd")}} ).Created

Get-ADComputer -Server $Server -Identity BlahBlah -Properties Created | 
  Select-Object @{N="Created";E{$_.Created.ToString("yyyy-MM-dd")}} |
    Select-Object -Expand Created

参数名可以简写,只要能唯一标识即可,还有简写(大写字母)所以-EA就是-ErrorAction

计算得出的 属性 IMO 在这里没有意义,因为它是唯一的输出,所以这也应该这样做:

Get-ADComputer -Server $Server -Identity BlahBlah -Properties Created | 
  ForEach-Object {$_.Created.ToString("yyyy-MM-dd")}

补充,提供有效的解决方案:

至于为什么你的代码不起作用:

虽然 Select-Object-Property 参数接受定义 哈希表 (例如在您的代码中),-ExpandProperty参数只接受属性name,作为string.

因此,您的哈希表只是 stringified,导致字符串文字 System.Collections.Hashtable,导致 Select-Object 抱怨,因为没有 [=79] =] 那个名字。

-ExpandProperty 目的是仅输出一个 属性 而不是带有 [=79= 的自定义对象].
因此,您不需要通过 Select-Object 绕行,只需 使用值输出脚本块 - { $_.Created.ToString("yyyy-MM-dd") } - 直接使用 ForEach-Object 代替,如 LotPings 答案底部所示。


但是,使用 ForEach-Object 时您放弃了一个模糊的功能:Select-Object 允许 组合 -ExpandProperty-Property,在这种情况下,通过 -Property 指定的属性将作为 NoteProperty 成员添加到通过 -ExpandProperty 指定的 属性 的 value :

PS> $val = [pscustomobject] @{ one = 'uno'; two = 2 } |
      Select-Object -ExpandProperty one -Property two; $val; $val.two
uno
2

注意输出 string'uno' 如何附加了输入对象 .two 属性 的副本。

要用 ForEach 模拟需要更多工作:

PS> $val = [pscustomobject] @{ one = 'uno'; two = 2 } | ForEach-Object {
      $_.one + '!' | Add-Member -PassThru two $_.two
    }; $val; $val.two
uno!
2