在PowerShell中选择数组的所有对象上一个属性的值 [英] Select the values of one property on all objects of an array in PowerShell

查看:318
本文介绍了在PowerShell中选择数组的所有对象上一个属性的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,我们有一个对象数组$ objects.假设这些对象具有名称"属性.

Let's say we have an array of objects $objects. Let's say these objects have a "Name" property.

这就是我想做的

 $results = @()
 $objects | %{ $results += $_.Name }

这可行,但是可以用更好的方法做到吗?

This works, but can it be done in a better way?

如果我做类似的事情:

 $results = objects | select Name

$results是具有Name属性的对象的数组.我希望$ results包含一个Names数组.

$results is an array of objects having a Name property. I want $results to contain an array of Names.

有更好的方法吗?

推荐答案

我认为您也许可以使用Select-ObjectExpandProperty参数.

I think you might be able to use the ExpandProperty parameter of Select-Object.

例如,要获取当前目录的列表并仅显示Name属性,可以执行以下操作:

For example, to get the list of the current directory and just have the Name property displayed, one would do the following:

ls | select -Property Name

这仍然返回DirectoryInfo或FileInfo对象.您始终可以通过管道连接到获取成员来检查通过管道的类型>(别名gm).

This is still returning DirectoryInfo or FileInfo objects. You can always inspect the type coming through the pipeline by piping to Get-Member (alias gm).

ls | select -Property Name | gm

因此,要将对象扩展为要查看的属性类型的对象,可以执行以下操作:

So, to expand the object to be that of the type of property you're looking at, you can do the following:

ls | select -ExpandProperty Name

对于您而言,您可以执行以下操作以使变量为字符串数组,其中字符串为Name属性:

In your case, you can just do the following to have a variable be an array of strings, where the strings are the Name property:

$objects = ls | select -ExpandProperty Name

这篇关于在PowerShell中选择数组的所有对象上一个属性的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆