i would like to sort my Server-list in quite an unusal way. So far i managed to sort my CSV-file with Powershell like this:
import-csv path | sort-object Name | export-csv path -useculture -notypeinformation
->
Name,IP,...
Server100,stuff,...
Server200,stuff,...
Server300,stuff,...
vServer100,stuff,...
vServer200,stuff,...
vServer300,stuff,...
But i would really like to sort them like this:
Name,IP,...
Server100,stuff,...
vServer100,stuff,...
Server200,stuff,...
vServer200,stuff,...
Server300,stuff,...
vServer300,stuff,...
Read something about regex, but i'm quite new to scripting and can't figure it out.
CodePudding user response:
You can pass a scriptblock or a calculated property definition as the -Property
argument:
Import-Csv $path |Sort-Object { $($_.Name -replace '\D') }, Name |...
The regex operation $_.Name -replace '\D'
will take the value of the Name
property (eg. vServer100
) and remove any non-digits.
The
in front of the subexpression converts the resulting string (eg. "100"
) to a number (eg. 100
).
After sorting on this number, Sort-Object
will then order by Name
, so ServerXXX
appears before vServerXXX