Creating objects with a cast in PowerShell 3.0
Starting with PowerShell 3.0, we now have another cool way to create new objects. We can create them by calling the default constructor of the type and initializing its properties with a cast:
[System.Drawing.Point]@{X=1;Y=2}
We put the type in square brackets and assign it a hash table containing the properties we want to initialize. Looking at this example got me thinking, how can I know the properties I can set for a specific class/type? As a learning tool, I wrote the Get-HashType function. Give it a type name and it will tell you the properties you can set.
#requires -Version 3.0
function Get-TypeHash
{
[CmdletBinding()]
[OutputType('System.String')]
Param(
[Parameter(
Mandatory=$true,
Position=0,
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true)]
[Alias('FullName')]
[Type]$TypeName
)
process
{
try
{
if($TypeName.IsClass -and !$TypeName.GetConstructor([Type]::EmptyTypes))
{
throw "Constructor not found. Cannot find an appropriate `
constructor for type '$TypeFullName'"
}
$TypeFullName = $TypeName.FullName
$WriteableProperties = $TypeName.GetProperties() | where CanWrite
if($WriteableProperties.Count -gt 0)
{
$hash = "[$TypeFullName]@{"
$WriteableProperties | ForEach-Object {
$hash+="`n`t{0} = <{1}>" -f $_.Name,$_.PropertyType
}
$hash+"`n}"
}
else
{
Write-Warning "No writable properties found for type '$TypeFullName'"
}
}
catch
{
Write-Error $_
}
}
}
PS> Add-Type –Assembly System.Drawing
PS> Get-TypeHash –TypeName System.Drawing.Point
[System.Drawing.Point]@{
X = <System.Int32>
Y = <System.Int32>
}
The output includes the writeable properties of the type and their corresponding value type. Copy the output, assign the values and paste it back to the console. This will create the object:
PS> [System.Drawing.Point]@{
>> X = 1
>> Y = 1
>> }
>>
IsEmpty X Y
------- - -
False 1 1
The function works for types that have a default constructor and for structure types. In the example above, System.Drawing.Point is a structure.