如何在PowerShell中从此数组中获取唯一值?

时间:2012-05-19 17:32:19

标签: string powershell unique

为什么以下代码返回$null?我试图存储唯一的值。

$DailyPathsToDelete = @("C:\temp\IMG000483\","C:\temp\IMG000483\")
$DailyPathsToDelete = Select-Object $DailyPathsToDelete -Unique 

3 个答案:

答案 0 :(得分:9)

简答:

要获取所有唯一路径,您应该将$DailyPathsToDelete传送到Select-Object并设置Unique开关。

$DailyPathsToDelete = $DailyPathsToDelete | Select-Object -Unique

更长的回答:

1。为什么它不起作用

运行脚本$DailyPathsToDelete后等于$null,因为(在脚本的第二行)$DailyPathsToDelete绑定到参数PropertyInputObject cmdlet的参数Select-Object 未明确,这就是调用Select-Object的结果为$null的原因。

可以通过跟踪表达式轻松验证:

Trace-Command -psHost -Name ParameterBinding { Select-Object $DailyPathsToDelete -Unique}

给出:

DEBUG: ParameterBinding Information: 0 : BIND NAMED cmd line args [Select-Object]
DEBUG: ParameterBinding Information: 0 :     BIND arg [True] to parameter [Unique]
DEBUG: ParameterBinding Information: 0 :         COERCE arg to     [System.Management.Automation.SwitchParameter]
DEBUG: ParameterBinding Information: 0 :             Parameter and arg types the same, no coercion is needed.
DEBUG: ParameterBinding Information: 0 :         BIND arg [True] to param [Unique]     SUCCESSFUL
DEBUG: ParameterBinding Information: 0 : BIND POSITIONAL cmd line args [Select-Object]
DEBUG: ParameterBinding Information: 0 :     BIND arg [System.Object[]] to parameter [Property]
DEBUG: ParameterBinding Information: 0 :         BIND arg [System.Object[]] to param [Property] SUCCESSFUL
DEBUG: ParameterBinding Information: 0 : MANDATORY PARAMETER CHECK on cmdlet [Select-Object]
DEBUG: ParameterBinding Information: 0 : CALLING BeginProcessing
DEBUG: ParameterBinding Information: 0 : CALLING EndProcessing

2。如何解决

使用Select-Object

$DailyPathsToDelete = $DailyPathsToDelete | Select-Object -Unique

使用Sort-Object

$DailyPathsToDelete = $DailyPathsToDelete | Sort-Object -Unique

第3。如何解决问题

我建议不要在您的方案中使用Get-Unique,因为Windows本地文件系统(NTFS,FAT和变体)不区分大小写。

示例:

$DailyPathsToDelete = @("C:\temp\IMG000483\","C:\Temp\IMG000483\")
PS C:\> $DailyPathsToDelete | get-unique
C:\temp\IMG000483\
C:\Temp\IMG000483\

答案 1 :(得分:3)

您可以尝试:

$unique = $DailyPathsToDelete | Get-Unique

答案 2 :(得分:3)

  1. 使用Get-Unique,gotcha - Get-Unique区分大小写,您还必须先对列表进行排序!

    $DailyPathsToDelete = $DailyPathsToDelete | Sort-Object | Get-Unique

  2. 使用Select-Object

    $DailyPathsToDelete = $DailyPathsToDelete | Select-Object -Unique

  3. 使用Sort-Object

    $DailyPathsToDelete = $DailyPathsToDelete | Sort-Object -Unique