Ironman Software Forums
Continue the conversion on the Ironman Software forums. Chat with over 1000 users about PowerShell, PowerShell Universal, and PowerShell Pro Tools.
PowerShell does some magical things when it comes to string conversion. Understanding a little bit about how it works can help you make sense of what’s happening in your scripts.
Some of the basic operations that you may encounter when converting between types in PowerShell may be examples such as dates, versions and numbers.
[int]$Number = "123"
[DateTime]$DateTime = '10-12-2021'
[Version]$Version = '1.0.1'
PS > $Number
123
PS > $DateTime
Tuesday, October 12, 2021 12:00:00 AM
PS > $Version
Major Minor Build Revision
----- ----- ----- --------
PowerShell takes care of these various conversions by either using the .NET constructor or the parse method of each type. You can get a similar result by using the parse methods directly.
$Number = [int]::Parse('123')
$DateTime = [DateTime]::Parse('10-12-2021')
$Version = [Version]::Parse('1.0.1')
In some scenarios, the casting of a string does more complicated operations. This is the case with type accelerators like XML
and WMI
.
In these cases, the parse or constructor is not used directly but instead internal operations convert to the destinate type.
[xml]$Xml = "<root><nested></nested></root>"
PS > $Xml | Get-Member
TypeName: System.Xml.XmlDocument
Certain types, like DateTime
, provide additional methods for parse types. You can take advantage of these .NET Methods by calling them directly rather than casting.
For example, you can call the ParseExact
method of DateTime
to convert a custom date and time string to a DateTime
object.
PS > [DateTime]::ParseExact('20211012', 'yyyyMMdd', $Host.CurrentCulture)
Tuesday, October 12, 2021 12:00:00 AM
Conversion can also happen in the opposite direction. If you have objects that you convert to strings, the ToString
method will be called for the object. Each object type can implement ToString
differently so you may have different results.
Versions for example, will return a friendly version string.
[Version]$Version = '1.0.1'
[string]$Version
# Returns 1.0.1
Find this useful? Please consider sharing this article. Have a question about PowerShell? Contact us and we'll write a post about it.
Continue the conversion on the Ironman Software forums. Chat with over 1000 users about PowerShell, PowerShell Universal, and PowerShell Pro Tools.
Receive once-a-month updates about Ironman Software. You'll learn about our product updates and blogs related to PowerShell.