Powershell相当于LINQ的Select命令?

时间:2022-01-13 15:46:17

I am trying to run the following Powershell script.

我正在尝试运行以下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}

The issue is $computers is not a string[] like -ComputerName expects. It really is a Array of ADComputer with one paramter called name.

问题是$ computers不像字符串[] --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
}

What is the correct way to get a array of strings for the names? If I was in C# I know it would be

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

string[] computerNames = computers.Select(computer => computer.name).ToArray();

but I want to learn how to do it in Powershell correctly.

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

1 个解决方案

#1


13  

You can use

您可以使用

Select-Object -ExpandProperty Name

or (probably the closest equivalent)

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

ForEach-Object { $_.Name }

Note that to force the result to be an array (e.g. if you want access to its Count property), you should surround the expression with @(). Otherwise the result might be an array or a single object.

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

#1


13  

You can use

您可以使用

Select-Object -ExpandProperty Name

or (probably the closest equivalent)

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

ForEach-Object { $_.Name }

Note that to force the result to be an array (e.g. if you want access to its Count property), you should surround the expression with @(). Otherwise the result might be an array or a single object.

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