Forcing data types

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:

Forcing data types

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 ...

Get Mastering Windows PowerShell Scripting now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.