While developing scripts, you may run into instances where you may want to force a specific data type. This is helpful in cases where PowerShell automatically interprets the output from a command incorrectly. You can force data types by the use of brackets specifying a data type and a variable.
To force a string data type, execute the following command:
[string]$myString = "Forcing a String Container" $myString
The output of this is shown in the following screenshot:
The preceding command forces the string data type to the $myString
variable. The result is that the $myString
variable will always remain a string. It is important to know that if the object or item that you are trying to force to a data type doesn't have a direct conversion to that data type, it will throw an error or exception. This would be the case if you try to insert a string into an integer data type.
To force a string data type and generate a data exception, execute the following command:
[int]$myInt =...