Type and type conversion

Type conversion in PowerShell is used to switch between different types of a value. Types are written between square brackets, in which the type name must be a .NET type, or a class, or an enumeration, such as a string, an integer (Int32), a date (DateTime), and so on.

For example, a date may be changed to a string:

PS> [String](Get-Date)
10/27/2016 13:14:32

Or a string may be changed into a date:

PS> [DateTime]"01/01/2016"

01 January 2016 00:00:00

In a similar manner, variables may be given a fixed type. To assign a type to a variable, the following notation is used:

[String]$thisString = "some value" 
[Int]$thisNumber = 2 
[DateTime]$date = '01/01/2016' 

This adds an argument type converter attribute to the variable. The presence of this converter is visible using Get-Variable, although the resultant type is not:

PS> [String]$thisString = "some value"
(Get-Variable thisString).Attributes

TransformNullOptionalParameters TypeId
------------------------------- ------
True System.Management.Automation.ArgumentTypeConverterAttribute

Subsequent assignments made to the variable will be converted into a string. This remains so for the lifetime of the variable: until the session is closed, the variable falls out of scope, or the variable is removed with Remove-Variable.

Setting the variable value to $null does not remove the type conversion attribute. This can be seen here:

PS> [String]$thisString = 'A string value'
$thisString = $null
$thisString = Get-Process powershell
$thisString.GetType()


IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True String System.Object

PowerShell's type conversion is exceptionally powerful. When converting a value, PowerShell uses the following conversions:

  • Direct assignment
  • Language-based conversion
  • Parse conversion
  • Static create conversion
  • Constructor conversion
  • Cast conversion
  • IConvertible conversion
  • IDictionary conversion
  • PSObject property conversion
  • TypeConverter conversion
More about type conversion:
The conversion process is extensive but there is documentation available. The preceding list can be found on an MSDN blog:
https://blogs.msdn.microsoft.com/powershell/2013/06/11/understanding-powershells-type-conversion-magic/
Experimentation with the process is a vital part of learning.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.39.60