12.2. Casting Strings to Other Classes

Once you have processed strings emitted from traditional applications and suitably manipulated them you may want to explicitly convert suitable strings to other datatypes. The following sections provide several examples of doing that.

12.2.1. URI

Given a suitably structured string, you can create a .NET URI object by using the technique shown in this example.

$a = "http://www.microsoft.com"
[URI]$c = $a

Typing

$c

causes the properties of the URI object to be displayed, as shown in Figure 12-31.

Figure 12.31. Figure 12-31

You can convert the $a variable to a URI object by using the following command:

$a = [URI]$a

12.2.2. datetime

If you enter a string which is a valid datetime value, you can easily cast it to the datetime datatype. That then allows you to access the properties of a datetime object. The following example shows how:

[System.Datetime]$a = "2006/12/31"

You can then access properties of the datetime object, such as the DayOfWeek property:

$a.DayOfWeek

Figure 12-32 shows the result of executing the preceding commands.

Figure 12.32. Figure 12-32

You need to be careful that you know the meaning of the string you cast to a DateTime object. Some dates are ambiguous, meaning one thing in one locale and having another meaning in another ...

Get Professional Windows® PowerShell 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.