Summary: Honorary Scripting Guy, Sean Kearney, continues his series about using Windows PowerShell to build scripts to automate DiskPart.
Hey, Scripting Guy! I saw yesterday how you could pull information from DISKPART with Windows PowerShell. I noticed the size of the disks was shown in GB or MB. Is there any way to convert that to tell the REAL size of the Disk?
—SH
Hello SH,
Honorary Scripting Guy, Sean Kearney. I’m here filling in for our good friend, Ed Wilson. It seems that he is looking for some paint for his new Tie House. He’s asking if anybody has “tie dye.”
Alright,. on with DiskPart automation…
Note This is Part 3 in a series. If you are behind, read:
- Automating DiskPart with Windows PowerShell: Part 1
- Automating DiskPart with Windows PowerShell: Part 2
If you were watching closely, the information we obtained for the size of the disk was delivered in the following fashion:
128GB
75MB
42KB
Although as a human, I can read that and understand that one is larger than the other, to make this useful we need to convert this to an actual integer. After it is converted, we can actually compare the size against a predefined parameter.
Fortunately, in Windows PowerShell, we have some built-in aliases for kilobytes (KB), megabytes (MB), and gigabytes (GB). So all we have to do is grab the final two characters, which will contain the multiplier, and use a Switch statement to quickly swap values. We can then grab the string with the numeric value for the physical size, and convert it to an integer. First off—how many characters are in the value?
$LENGTH=$SIZE.length
Now grab the last two characters, which will contain KB, MB, or GB:
- $MULTIPLIER=$SIZE.substring($length-2,2)
Now grab the remaining part at the beginning, which will be the numbers:
$INTSIZE=$SIZE.substring(0,$length-2)
Pass the $Multipier you found into a simple switch statement and swap the make believe world for the real world:
SWITCH($MULTIPLIER)
{
KB { $MULT = 1KB }
MB { $MULT = 1MB }
GB { $MULT = 1GB }
}
So now that we can simply multiply things and get the actual size for the disk, we’re going to enforce the result as an integer to make sure there’s no messy decimals in our output:
$DISKTOTAL=([convert]::ToInt16($intsize,10))*$MULT
Coolness! Now all we need to do is put all of this together into a function to return all of this as objects, and perhaps a bit more? Tune in tomorrow for our next episode of “Hey, Scripting Guy.”
I invite you to follow us on Twitter and Facebook. If you have any questions, send email to Ed at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.
Sean Kearney (filling in for our good friend Ed Wilson),
Honorary Scripting Guy, Windows PowerShell MVP
…and good personal friend of the BATCHman