The type operators are designed to work with .NET types. The following operators are available:
- As:
-as
- Is:
-is
- Is not:
-isnot
The -as
operator is used to convert a value into an object of the specified type. The operator returns null
(without throwing an error) if the conversion cannot be completed.
For example, the operator may be used to perform the following conversions:
"1" -as [Int32] 'String' -as [Type]
The -as
operator can be useful for testing whether or not a value can be cast to a specific type, or whether a specific type exists.
For example, the System.Web
assembly is not imported by default and the System.Web.HttpUtility
class does not exist. The -as
operator may be used to test for this condition:
PS> if (-not ('System.Web.HttpUtility' -as [Type])) { Write-Host 'Adding assembly' -ForegroundColor Green Add-Type -Assembly System.Web } Adding assembly