PowerShell belongs to a dynamic, not strongly typed-language class, meaning you are not required to declare the data type of variables. Simply put, PowerShell is smart enough to determine the data type on the fly.
Again, it is not required to specify the object type, but it doesn’t mean you can’t. Some scenarios may still strongly type the object, especially when converting to another type, such as our topic in this post.
Table of Contents
PowerShell is So Smart. It Just Works!
PowerShell can automatically determine the variable type when performing various actions on a variable, but this doesn’t always work well and correctly. There are instances when an object property may seem obvious, like “TotalItemSize” or “TotalUsers”, which are expected to be integer values, only to discover that their data type is a string.
The first question is, how do you know the object’s data type? Let’s find out.
For example, let’s create two sample variables and assign the same value.
# Create variables and assign values $a = 1 $b = '1'
# Display the variable values
$a
$b
As you can see, both variables return the exact value of 1. If so, we can use these values in a mathematical operation. Let’s see by adding these two values.
$a + $b
It worked!
There’s no error. An addition was performed on the two values and returned the correct result. Does that mean these two values are of the same data type? The answer is no, and here’s how you can find out.
$a.GetType() $b.GetType()
As you can see, PowerShell automatically assigned $a as an Int32 (32-bit integer) and $b as a String. So, they are different, after all.
This demonstration is just one example of how smart PowerShell is when handling objects and data types. It can evaluate expressions and make decisions on how to handle them. In this case, PowerShell understands that you want to add 1 and ‘1’ together.
But just because PowerShell could doesn’t mean you should rely on this automatic determining of types and expressions. Significantly when scripting and working on multiple data types, it would benefit you to cast values as the intended types to avoid debugging headaches.
Hint. Other popular data types in PowerShell:
-
[string]
-
[char] — ASCII character code
-
[bool] — “True” or “False”;
-
[int] — 32-bit number;
-
[long] — 64-bit number;
-
[decimal] — a floating-point number of 128 bits and a d at the end;
-
[double] — 8-bit floating point number;
-
[single] — 32-bit floating point number;
-
[DateTime] — Powershell datatype storing date and time;
-
[array] — PowerShell array;
-
[hashtable] — hash table;
-
[pscustomonject] — an array of type keys and values.
How to Convert String to Integer in PowerShell?
If you try to explicitly assign a string value to a numeric variable or try to perform other numeric operation, you get an error:
[int]$number = 'Ten'
MetadataError: Cannot convert value “Ten” to type “System.Int32”. Error: “The input string ‘Ten’ was not in a correct format.”
There are several ways to convert the string to an integer, giving the same result.
Let’s say you have a variable containing a string (type System.String):
$stringN = "777" $stringN.GetType().FullName
The screenshot below confirms that “777” is not a number but a word.
You can convert the string to integer using these techniques.
- Strongly type the variable:
[int]$stringN
([int]$stringN).GetType().FullName
- Using the [int]::Parse() method:
[int]::Parse($stringN)
([int]::Parse($stringN)).GetType().FullName
- Using the <value> -as [datatype] statement:
$stringN -as [int]
($stringN -as [int]).GetType().FullName
- Calling the String.ToInt32() method:
$stringN.ToInt32($null)
($stringN.ToInt32($null)).GetType().FullName
- Using the [convert]::ToInt32() method:
[convert]::ToInt32($stringN)
([convert]::ToInt32($stringN)).GetType().FullName
Note. Learn how to use Group Policy to manage, add, modify, import, and delete registry keys. - Tip: The [convert] class allows you to convert a value not only to Int32, but also to other integer data types:
- [convert]::ToInt16 — Signed 16-bit integer (short)
- [convert]::Int64 — Signed 64-bit integer (long)
- [convert]::UInt32 — Unsigned 32-bit integer (uint)
- [convert]::UInt64 — Unsigned 64-bit integer (ulong)
Check for Integer Input in PowerShell Scripts
In some cases, when you get the value of a variable from the user or any other source, you need to check if the input is an integer value. You can use the below PowerShell function to validate integer input in PowerShell scripts. This function takes a value as input and checks if it corresponds to the Integer32 data type (after conversion).
Function IsInteger { param( [string]$vInteger ) Try { $null = [convert]::ToInt32($vInteger) return $True } Catch { return $False } }
You can check the correctness of the function on the test data:
IsInteger "five" IsInteger "70.1" IsInteger "100" IsInteger 100
Converting Formatted String to Integer
Sometimes the supposed numeric value is shown as a formatted string, such as those with “,” for thousands notation.
$value1 = "120,830,200" $value2 = "120,830,200 (bytes)"
You understand these values, but none of the string-to-integer conversion methods we learned will work because these are not purely numbers.
In this case, you must employ string manipulation to clean up the values and retain the numbers only.
Specific to the above examples, one way is to use the String.Replace() method.
$value1.Replace(',',$null) $value2.Replace(',',$null).Replace(' (bytes)',$null)
Since the values have been cleaned up, you can now convert them to integers using any methods we discussed.
[int]($value1.Replace(',',$null)) $value2.Replace(',',$null).Replace(' (bytes)',$null) -as [int]
Conclusion
In conclusion, PowerShell’s dynamic and adaptable nature makes it a powerful tool for handling various data types and operations. While PowerShell can often determine the data type and perform operations seamlessly, it’s essential to be aware of potential type mismatches that can lead to unexpected outcomes.
The ability to automatically assign data types, as demonstrated by the example of adding an integer and a string, showcases PowerShell’s intelligent handling of expressions.
However, this automation doesn’t negate the importance of understanding and explicitly handling data types, especially when working with diverse data sets or in scripting scenarios. Explicitly casting values to their intended types, as we explored in this post, helps avoid potential debugging challenges.
We explored multiple methods when converting strings to integers, each providing similar results. These methods include strong typing, using static methods like [int]::Parse(), employing the -as [int] statement, and using methods from the [convert] class. We also discussed the significance of checking and validating integer inputs when interacting with users or external data sources.
1 comment
Useful tips
Thanks a lot