Powershell相当于LINQ的Select命令?

Sco*_*ain 16 .net c# linq powershell

我正在尝试运行以下Powershell脚本.

import-module ActiveDirectory

$computers = Get-ADComputer -filter * -SearchBase "OU=myOU,DC=vw,DC=local" | select-object name

Invoke-Command -ComputerName $computers -ScriptBlock {gpupdate /target:Computer}
Run Code Online (Sandbox Code Playgroud)

这个问题是$computers不是string[]-ComputerName预期.它实际上是一个ADComputer带有一个名为name的参数的数组.

# Get-ADComputer -filter * -SearchBase "OU=myOU,DC=vw,DC=local" | select-object name | Format-Custom

class ADComputer
{
  name = PC1
}

class ADComputer
{
  name = PC2
}

class ADComputer
{
  name = PC3
}
Run Code Online (Sandbox Code Playgroud)

获取名称字符串数组的正确方法是什么?如果我在C#,我知道它会

string[] computerNames = computers.Select(computer => computer.name).ToArray();
Run Code Online (Sandbox Code Playgroud)

但我想学习如何正确地在Powershell中做到这一点.

Joe*_*oey 18

您可以使用

Select-Object -ExpandProperty Name
Run Code Online (Sandbox Code Playgroud)

或(可能是最接近的等价物)

ForEach-Object { $_.Name }
Run Code Online (Sandbox Code Playgroud)

请注意,要强制结果为数组(例如,如果要访问其Count属性),则应使用包围表达式@().否则结果可能是数组单个对象.