0

i'm new to powershell so any help is much appreciated.

I have an list of strings (filenames) and they start with a number eg. "1. first file", "2. second file" ... "21. twenty-first file".

and I want to sort it in the order of the starting number. But when I do "$List | sort {$_.Name} -Unique" it will start with "1. " and then the next item is "11." instead of "2."

Please help.

3 Answers 3

1

Here is one way to do it:

$test = @('1. First', '2. Second', '11. Eleventh')
$sort = @()
foreach($item in $test){
  $item -match '^(\d+).*'
  $temp = New-Object PSCustomObject -property @{'Number' = [int]$matches[1]}
  $sort += $temp
}
$sort | Sort-Object Number | Select-Object Data
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, the only thing is that you missed a "}" after "[int]$matches[1]". But with that fixed it worked great! Thanks a lot :)
Woops, yeah I tested it as a oneliner at the prompt and missed that when I changed it to a script.
0

Here's another option:

$col = @(
'1. first file'
'2. second file'
'11. eleventh file'
'21. twenty-first file'
)

$ht = @{}
$col | foreach {$ht[$_ -replace '\D+$'] = $_}
[int[]]$ht.keys | sort | foreach {$ht["$_"] }

1. first file
2. second file
11. eleventh file
21. twenty-first file

Comments

0

To simplify the previous answer a little, you could do this:

$test | Sort-Object -Property @{ Expression={[int]$_.substring(0,$_.IndexOf('.'))}; Ascending=$true }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.