Coming from JavaScript, it feels like adding a function to a hashtable in PowerShell shouldn't be that complicated.

Took a bit of googling, but it's not. For PS 3+...

$h = @{ spam = "spiced"; ham = "green" };
$obj = [PSCustomObject]$h | 
Add-Member -MemberType ScriptMethod -Value { $this.spam } -Name foo -PassThru

Create hashtable. Cast to PSCustomObject (this is the same as saying New-Object psobject -Property $h, which I might end up preferring for backwards compat -- and for the consistency of using a cmdlet). Pipe to Add-Member where you add your .NET method. Profit.

You can kinda tell it's [C#-ish] .NET because you're into the this paradigm inside of the scriptblock.

Want a function with params? Can do.

$h = @{ spam = "spiced"; ham = "green" };
$obj = [PSCustomObject]$h | 
Add-Member -MemberType ScriptMethod -Value { $this.spam } -Name foo -PassThru | 
Add-Member -MemberType ScriptMethod -Value { 
    param( $first, $second) 
    "first is $first, second is $second" 
} -Name DoStuff -PassThru;

That adds two methods, the second with params.

Calling the function is also painfully .NET-ese, right back to the parens that your first few weeks of PowerShelling taught you to avoid (original, pre-fiddled sauce):

PS> $
PS> $obj.DoStuff("first", "second")
first is first, second is second

I really dislike how that paradigm shift (from PowerShell modules to unabashedly .NET functions) operates, but I guess the point is that a Verb-Description is never going to belong to an object. They are tied to no specific noun. Yet PowerShell still feels a little like a kludge that too often gives up and dumps its problems directly into .NET. That's good, since I'm a .NET programmer, but bad in that PowerShell feels imcomplete and kludgey, and its culture (I think even the new-as-of-PS 3 [PSCustomObject] cast is kludgey, and that's straight from the Scripting Guy as the preferred method of doing this) is wrapping itself around these sorts of kludges instead of pushing forward PS development and best practices.

Maybe dumping into .NET is good. Idk. But it's sure grafty, grafty like the Tree of 40 Fruit.

Thanks to these links:

Labels: ,