arrays - 如果提供了 1 个值,Powershell Get-Unique 会在数组中拆分字符串
问题描述
我有一个 PowerShell 脚本,如果仅将 1 个字符串馈送到数组,则该脚本会失败,因为它在使用 Get-Unique 和/或 Sort-Object 时将其拆分为字符。但是,如果提供了多个值,则它会按预期工作。例如:
预期行为:
PS X:\> $t = @("asd","bcd") | Get-Unique
PS X:\> $t[0]
asd
PS X:\> $t[1]
bcd
意外(有 1 个值):
PS X:\> $t = @("asd") | Get-Unique
PS X:\> $t[0]
a
PS X:\> $t[1]
s
PS X:\> $t[2]
d
有人可以解释为什么会发生这种情况以及如何预防吗?我很感激任何输入,因为我的搜索没有带来任何运气。
谢谢
解决方案
Get-Unique
doesn't split anything - it just returns the one string value as is, and as a result, $t
now contains a scalar string, not an array:
PS ~> $t = "asd" |Get-Unique
PS ~> $t.GetType().FullName
System.String
PS ~> $t
asd
But as soon as you try to access the string value with the index accessor []
, it returns the individual [char]
value found at the given index.
If you want to ensure the output from Get-Unique
(or Sort-Object
or any other command that might return 0, 1, or more objects as output), wrap the pipeline in the array subexpression operator @()
:
PS ~> $t = @( "asd" | Get-Unique )
PS ~> $t[0]
asd
推荐阅读
- php - laravel 为用户设置个人资料页面错误属性 [user] 在此集合实例上不存在
- php - 我可以使用 API 在移动设备中使用服务器端支付集成吗
- php - 数据表未显示来自查询的所有数据
- javascript - 切换表格的显示:不是第一列
- java - 如何在数组中打印 [ ] (Java)
- visual-studio - 使用 Visual Studio 2017 Docker build 未将 site.css 样式应用于 Docker 映像
- c# - 将 C# 流式接口转换为 VB.NET 中的代码
- amazon-web-services - 使用 AWS cognito 将自己的 api 作为第三方
- javascript - 将 data-dismiss="modal" 绑定到键单击
- c# - 当值不是数字时,自定义数字验证无法正常工作