Search code examples
arrayspowershellsortingsort-object

PowerShell, use Sort-Object to return an Array


I've looked at various sites that suggest that Sort-Object will return an array. This is not what I am seeing as when I do the below, the final output caused by the Sort-Object is just a single string. How can I sort the array into another array instead of to a string?

$myprogs = Get-ChildItem D:\MyPath\MyPrograms
$myprognames = foreach ($i in $myprogs) { $i.FullName -replace "D:\\MyPath\\MyPrograms\\", "" }
# At this point, $myprognames is a normal array
$myprognames = $myprognames | Sort-Object -Unique
$myprognames
# At this point, $myprognames is a single string with all elements stuck together, and if I select an element, like $myprognames[17], I will just get a single character as it's a string.

Solution

  • If I assume right you want something similar to this:

    $myprogs = 
        Get-ChildItem 'D:\MyPath\MyPrograms' |
            Select-Object -Property *,
                @{Name = 'ShortenedPath'; Expression = {$_.FullName -replace ([regex]::escape('D:\MyPath\MyPrograms'))}}
    $MyProgNames = $myprogs | 
        Sort-Object -Property ShortenedPath -Unique
    

    Of course you should list all properties you're actually after instead of using -Property *

    According to your comment you're actually looking for the names of the folders sorted, right? If that's the case you're overcomplicating this a lot. ;-)

    $myprogs = 
        Get-ChildItem 'D:\MyPath\MyPrograms' |
            Select-Object -Property Name |
               Sort-Object -Property Name -Unique