Skip to content

Instantly share code, notes, and snippets.

@josheinstein
Created October 9, 2012 15:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save josheinstein/3859588 to your computer and use it in GitHub Desktop.
Save josheinstein/3859588 to your computer and use it in GitHub Desktop.
I wish PowerShell object literals worked like this...
# PowerShell 3 adds the new [PSCustomObject] pseudo type attribute which
# lets you declare an object literal using a syntax very similar to that
# of an ordinary Hashtable. (There's also a new [Ordered] attribute that
# creates a hash table with the order of keys preserved.)
#
# But it only lets you declare an object literal with NoteProperties.
# What I would really love to have seen is the syntax look for script
# blocks and create ScriptProperties out of them if there is no param
# block or ScriptMethods out of them if there is a param block.
#
# In the example below, I show how this can be done with the following
# syntax: New-PSObject ([Ordered]@{ ... })
#
# But it would have been nice if [PSCustomObject]@{ ... } worked this way.
function New-PSObject($Dictionary) {
$Obj = New-Object PSObject
foreach ($K in $Dictionary.Keys) {
$V = $Dictionary[$K]
if ($V -is [ScriptBlock]) {
if ($V.Ast.ParamBlock) {
$Obj | Add-Member ScriptMethod $K $V
}
else {
$Obj | Add-Member ScriptProperty $K $V
}
}
else {
$Obj | Add-Member NoteProperty $K $V
}
}
Return $Obj
}
New-PSObject ([Ordered]@{
X = 1
Y = 2
Z = { $This.X + $This.Y }
DoSomething = { param() "Did something!" }
}) | GM
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment