liveBook · Manning

Data conversion

As explained in Learn PowerShell in a Month of Lunches: Fourth Edition, Covers Windows, Linux, and macOS

Casting is the operation of treating a value as a specified type, optionally converting it to an object of that type.

Type conversion treats an existing value as a specified type, sometimes producing a new object. In PowerShell, casting a URI-shaped string with [Uri] turns it into a System.Uri object with useful properties such as Host, Port, and Scheme. section 11.2

Use these forms when working with different types:

  • Use -as to attempt conversion: 1000 / 3 -as [int]. Converting to an integer rounds the fractional value rather than simply truncating it. section 26.2.1
  • Place the value before -as and the target type in brackets, such as [string], [xml], [int], [double], or [datetime]. section 26.2.1
  • Use -is when you only need a True or False type check, such as "SRV02" -is [string] or (Get-Date) -is [datetime]. section 26.2.1

Convert a URL into a Uri object

Run [Uri]"https://github.com". PowerShell displays the resulting object's URI properties, including Scheme=https, Host=github.com, Port=443, and AbsoluteUri=https://github.com/.

How Learn PowerShell in a Month of Lunches: Fourth Edition, Covers Windows, Linux, and macOS covers it

How deep it goes
Explains conversion syntax, numeric rounding, URI object properties, and Boolean type tests without developing custom type or formatting files.
Examples
Demonstrates URI casting, integer conversion after division, and string, Boolean, and datetime type checks.
What it assumes
Assumes familiarity with running simple PowerShell expressions while teaching type names, casting syntax, and type checks directly.
What you can do after
Apply PowerShell casts with bracketed types, convert values using -as, and test types using -is.
How it connects
Links type conversion to PowerShell objects, URI properties, type testing, and formatting.

Also explained in

Compare how 21 books explain data conversion →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn PowerShell in a Month of Lunches: Fourth Edition, Covers Windows, Linux, and macOS. The section links point to the parts of the book it draws on.