首页 > 解决方案 > 如果提供了 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

有人可以解释为什么会发生这种情况以及如何预防吗?我很感激任何输入,因为我的搜索没有带来任何运气。

谢谢

标签: arraysstringpowershell

解决方案


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

推荐阅读