Sort Physical Disks by FriendlyName

Hi Folks,

Sorry but the syntax for trying to do this has gotten the better of me tonight.

I have some Azure disks I want to work on that I’ve retrieved like this:

$uninitializedDisks = Get-PhysicalDisk -CanPool $true

That returns 11 disks. I want to select the first two drives based on a numeric ordering of the FriendlyName. For example, if I just view the value of:


The friendly names appear as:


and so on. I want to retrieve:


I was getting to really messy syntax like:

$uninitializedDisks | sort-object -Property @{Expression={int.Parse($_FriendlyName.ToString().SubString(12, $_FriendlyName.ToString().Length - 12).PadLeft(2,“0”))}} | Select-Object -First 2

But still must have been doing something wrong.

Any help would be appreciated.

If they all have PhysicalDisk at the front, can’t a normal

$UnitializedDisks | Sort

No, because “11” will sort before “2.” A “plain” sort will only work if it’s something like “PhysicalDisk01” and so forth.

If that’s not the case, I would probably do the Select-Object first, adding a custom property that contains only the disk sequence number, as an integer. THEN I’d sort on that custom property. So, similar to what you’re doing, but reversing the logic a bit. Doing it my way will also make it easier to see if your “messy syntax” is working the way you think it is ;).

But you’re overdoing the syntax a bit. For example…


Will cast something as an integer; you don’t need all the Parse() method stuff. You can also get rid of “PhysicalDisk” more easily.


Basically, just remove “PhysicalDisk” by replacing that string with an empty string. That’ll leave you with a numeric string, which is then case as an integer. You shouldn’t HAVE to pull a ToString() on it first, since the property value should already be a string. The ISE may not “see” it as a string as you’re typing, but it ought to run.

Thanks folks. The Replace option simplified it nicely. I also just didn’t have the sort-object -property syntax for the custom sort value correct. I’ve fixed it now and it looks good.