【问题标题】:PowerShell: Collection converted to array reporting array-value lengths instead of array-valuesPowerShell:集合转换为数组报告数组值长度而不是数组值
【发布时间】:2019-10-10 16:01:53
【问题描述】:
$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

【问题讨论】:

  • 更简单的重现方法:'a', 'aa', 'aaa' | select *。字符串只有一个属性:Length
  • +1 PetSerAl -- 我把这个例子写得非常复杂,因为它更能代表我在脚本中看到的问题(如果问题与我遇到的其他问题有关)做)。

标签: .net powershell collections


【解决方案1】:

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

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

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

PS> 'one' | Select-Object *

Length
------
     3

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

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

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

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

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

【讨论】:

  • @thepip3r:很高兴听到它有帮助;我知道从输出中看不出发生了什么。
猜你喜欢
  • 1970-01-01
  • 2019-08-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-05
  • 2015-10-18
  • 1970-01-01
  • 2019-04-12
相关资源
最近更新 更多