首页 > 解决方案 > PowerShell:集合转换为数组报告数组值长度而不是数组值

问题描述

$sample = @"
name,path,type
test1, \\server1\path1\test1.txt, 1
test2, \\server1\path1\test2.txt, 1
test3, \\server1\path2\test3.txt, 2
test4, \\server1\path1\test4.txt, 2
test5, \\server1\path3\test1.txt, 3
"@

$s = $sample | ConvertFrom-Csv

$g = $s | Group-Object -Property type
# $g[0].Group.GetType() reports as Collection`1

$t = $g[0].Group | Select -ExpandProperty Path
# $t.GetType() reports as Name=Object[], BaseType=System.Array

$t
# reports:
# \\server1\path1\test1.txt
# \\server1\path1\test2.txt

$t | Select *
# reports:
# Length
# ------
#    25
#    25

我在我的一个脚本中遇到了一个问题,我可以用以前的代码重现这个问题。我有一个来自 Import-Csv 的数组,其中包含一堆 UNC 路径。我根据不同的 CSV 属性标准对这些路径进行分组,然后尝试使用生成的 .Group 属性 Collection 对象对该组执行更多工作。我的问题是,如果我尝试对该对象执行任何操作,除了将其发送到控制台之外,该对象将报告为值长度而不是值本身。

例如:$t | Converto-Html -Fragment

任何人都可以解释发生了什么,与值相比,长度正在发射,最终如何解决这个问题以获取值而不是涉及 Group-Object、Group Properties 的长度?TIA

标签: .netpowershellcollections

解决方案


由于您正在使用-ExpandProperty,因此$t = $g[0].Group | Select -ExpandProperty Path将(一个数组)仅存储在 中的字符串值[string]实例)$t,即输入对象上的属性值。.path

Select *报告这些实例的属性[string](包装在[pscustomobject]实例中),并且假设字符串只有一个属性-.Length您只会看到这些长度值,而不是字符串的内容

一个简单的例子(报告字符串的长度'one',即,3):

PS> 'one' | Select-Object *

Length
------
     3

请注意,使用ConvertTo-Csv/会得到类似的结果Export-Csv,因为它们也会序列化其输入对象的属性:

PS> 'one' | ConvertTo-Csv
"Length"
"3"

如果省略该-ExpandProperty开关,您将获得具有包含感兴趣路径字符串的属性的[pscustomobject]实例:.Path

PS> $g[0].Group | Select Path

path
----
\\server1\path1\test1.txt
\\server1\path1\test2.txt

推荐阅读