Wednesday, June 10, 2015

How do you convert a string to integer in Powershell?


It is easy to convert a number represented as a string into an Integer.

Here is a string declaration:
$str1="123"

Declare the string in the command window is as shown:
PS C:\Users\Jayaram> $str1="123"  

The displayed value in the command window is as shown:
PS C:\Users\Jayaram> $str1
123

You can get to find the data type by running the following:
PS C:\Users\Jayaram> $str1.GetType().FullName
System.String

==============================
Now we convert this to an integer

The following line converts the string to an Integer
PS C:\Users\Jayaram> $foo=[INT]$str1

This is the value in the $foo variable
PS C:\Users\Jayaram> $foo
123

Now we get the type of data in $foo
PS C:\Users\Jayaram> $foo.GetType().FullName
System.Int32

Difference between GetType().FullName and just GetType()
 

PowerShell has intellisense support and you should make use of it in your coding as shown here:
After typing $foo insert a . and wait for the pop-up menu with various possible items as shown.

                                                                                                           
A string such as "555-5555-1212" is a string but will return an error as the variable is not in the correct format.
PS C:\Users\Jayaram> $str2="555-5555-1212"

PS C:\Users\Jayaram> $boo=[INT]$str2
Cannot convert value "555-5555-1212" to type "System.Int32". Error: "Input
string was not in a correct format."
At line:1 char:1
+ $boo=[INT]$str2
+ ~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvalidCastFromStringToInteger

No comments: