Reading Managing Records in Python
For many years there was no record type in the Python language […] Guido never considered that request […] "in real life you always need to add methods to your data, so just use a custom class"
In PowerShell you can create property bags two ways, Add-Member and Select-Object. Often you need a function that takes parameters and returns an object to hold some data. Typing this out takes time, tweaking and testing.
Below, New-Function generates your function. This example creates a function named New-Pair that takes two parameters, item1 and item2.
Notice the next line uses the newly created function.
New-Function 'New-Pair' 'item1 item2' New-Pair 1 2 | Format-Table -AutoSize
Another Example
New-Function creates a PowerShell function so parameter binding works too.
New-Function ` 'New-Person' 'FirstName LastName Address City State Zip' New-Person John Doe -Zip 10001
The Factory
Function New-Function ($name, $properties) { $parts = $properties.trim().split(' ') $parts | %{ $selectProperties += @" @{ Name = '$_' Expression = {`$$_} }, "@ } # simple way to remove the trailing comma $selectProperties = $selectProperties -Replace ",$", "" Invoke-Expression @" Function Global:$name { param(`$$($parts -join ',$')) New-Object PSObject | select $selectProperties } "@ }


{ 2 comments… read them below or add one }
You could simplify by taking an object array as second param and get away from the split method.
Good point, I modeled the Python approach. I’ll re-work it for a cleaner PowerShell version.
function ql {$args}
New-Function ‘New-Person’ ( ql FirstName LastName Address City State Zip )