Search code examples
powershellhashtablestatic-methods

How can I splat a hashtable directly from a class static method?


How can I get the same output as:

$ht = @{Object="Hi there";Foregroundcolor="Green"}
Write-Host @ht

without using a/the variable $ht ?

Don't get me wrong, I know how to use a basic CMDLet. I have a static method that generates dynamic hashtables. Look at this simplified example code:

class HashtableGenerator
{
    static [hashtable]Answer()
    {
        return @{Object="Hallo Welt";ForegroundColor="Green"}
    }
}
$ht = [HashtableGenerator]::Answer()
Write-Host @ht

This works just fine, but is it possible to get rid of the $ht variable, so the code would look something like this:

Write-Host @([HashtableGenerator]::Answer()) # Doesn't work

Solution

  • I'm pretty sure what you are looking to do is not possible at least at this time. Splatting is specific to hashtable and array variables explicitly. Not return values of functions, methods etc. Technet for splatting sort of supports this

    Splatting is a method of passing a collection of parameter values to a command as unit. PowerShell associates each value in the collection with a command parameter. Splatted parameter values are stored in named splatting variables, which look like standard variables, but begin with an At symbol (@) instead of a dollar sign ($). The At symbol tells PowerShell that you are passing a collection of values, instead of a single value.

    Using the @ outside of that will tell PowerShell to treat the results as an array. IIRC there is a semi related feature request to splat directly from a hashtable definition instead of saving to a variable first.


    Related question talking about splatting from a variable property: Splatting a function with an object's property