Building PowerShell Custom Objects Quick Tips

Let’s get right to the point. Here are a total of 4 simple tips to help you build custom PowerShell objects in both Version 2.0 and 3.0:

[sourcecode language=”powershell”]
##
## Tip 1 – You don’t need to use single quotes the labels:
##

$value01 = ‘Max’; $value02 = ‘Theresa’;
$hashobj = @{ `
label1 = $value01; `
label2 = $value02; `
};
$hashobj;

[/sourcecode]

[sourcecode language=”powershell”]
##
## Tip 2 – In PowerShell version 2.0, you can use the New-Object to convert the
## – Hash Object to a PSobject:
##

$NewPSObj = New-Object PSObject -Property $hashobj;
$NewPSObj.GetType();

$NewPSObj;

[/sourcecode]

[sourcecode language=”powershell”]
##
## Tip 3 – Better yet, you can include the Hash object code in the property
## parameter as a Scriptblock:
##

$NewPSObj2 = New-Object PSObject -Property @{ `
label1 = $value01; `
label2 = $value02; `
};

$NewPSObj2.GetType();

$NewPSObj2;

[/sourcecode]

[sourcecode language=”powershell”]
##
## Tip 4 – In PowerShell version 3.0, it gets better because you just add the
## accelator type [PSCustomObject] to the hash object and this will
## convert to a PSobject:
##

$value01 = ‘Max’; $value02 = ‘Theresa’;
$hashobj2 = [pscustomobject] @{ `
label1 = $value01; `
label2 = $value02; `
};
$hashobj2.GetType();

$hashobj2;

[/sourcecode]

Also, in this code you’ll see the use of the space follow by a tick ” `” which is a “line continuation”, and the semi-colon “;” which is commonly use as a line terminator. Both are optional but useful.