.net - 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
解决方案
由于您正在使用-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
推荐阅读
- python - 覆盖 Qt MouseEvent 但仅当类变量为 True 时
- java - 非空属性引用了一个瞬态值 Hibernate
- java - 如何在休眠中覆盖瞬态对象的哈希码和等于?
- jquery - 我的下拉菜单没有使用 jQuery 出现。有小费吗?
- r - 使用过滤器计算均值给出错误值
- visual-studio-code - Live-Server 在 Visual Studio Code 端口 5500 中不起作用
- lotus-notes - Notes 注册:如何在注册过程中使用 lotus 脚本创建副本邮件
- java - Java Servlet 头隐式对象
- python - TypeError: _init_subclassed_network() 在使用 TensorFlow Keras 时得到了一个意外的关键字参数“输入”
- reactjs - 在 this.props.history 更新后未设置 localStorage