Converting a String to an Integer In PowerShell

For a project I’m working on (more on this site very soon), I ran into an issue with PowerShell variables that kept me busy for a few hours. What I was trying to do is get input from an XML file, put that value into a variable and use it to assign it as a value for the maximum memory that a virtual machine could use. Sounds easy, right? Well, not really. What happened is that I would get a conversion error:

Input string was not in a correct format.

This indicates that something wasn’t matching during a conversion and needed to be fixed. Let’s me explain.

So the value from the XML file is read into a variable as text (string). Basically it comes down to this:

Conversions-image1

When we query using gettype() we clearly see that the value is of a string type. Now, this happens because I included the “MB” part. Normally when you put a size value like “1024MB” directly into a variable inside a script, PowerShell is smart enough to figure out what you are actually trying to do. Use a certain size in Megabytes, Gigabytes etc, and converts it automatically to an integer. But in this case the value of “1024MB” is just text. I thought that PowerShell would equally be smart enough that putting an [INT] in front of the variable would somehow convert it. That didn’t work as expected. Hence the error in the beginning of this post.

The solution I wanted to create is get the value and split it at the MB or GB part, leaving just the numbers. After I would have figured out what kind of value it would be, convert it to an integer by doing some math. It was during this experiment that I discovered an easier way. Just divide the string by 1 and PowerShell smartness kicks in again! See the magic at work:

Conversions-image2

So just by dividing it by 1 it’s converted to the correct integer type. How cool (and easy) is that!

Hope this trick can be put to good use and saves you a lot of research time!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s