Wednesday, November 7, 2018

Powershell: Calculated Properties


Posting for reference; a bit a colleague sent me in chat:
Subtle...but important trick...turning literal strings into objects with a property:

'apple','orange','banana' | Select-Object -Property @{ Name = 'FruitName'; Expression = {$_} }

This way, if I had a cmdlet that took -FruitName as a parameter and accepted pipeline input by name...I could use this to map into that parameter...

[...]

In powershell parlance that's called a "calculated property"

[...]

Normally, you'd use it to transform a property. So for instance, say an existing property was in bytes and you wanted it in MB

Name='MB'; Expression = {$_.Bytes / 1MB }

[...]

And then the other use I can think of is if you had objects that had say a property called 'Name' that was actually a service name...but the cmdlet you wanted to pipe into needed '-ServiceName' ...you could use the calculated property trick to make your objects have a 'ServiceName' property.

@{ Name = 'ServiceName'; Expression = {$_.Name} }
Creating pipeable commandlets is a bit out of my wheelhouse. Funny how often I pipe existing commandlets, but do not think of making mine that way.

No comments: