PowerShell / Modules

MIT License
111 stars 25 forks source link

[ThreadJob] [FeatureRequest] Add -ParameterList argument to allow "splatting" parameters to be passed to the threadjob #75

Open JustinGrote opened 4 years ago

JustinGrote commented 4 years ago

@PaulHigin This issue was moved from https://github.com/PaulHigin/PSThreadJob/issues/59

Currently there's no way to pass parameters to a threadjob scriptblock, you can pass arguments but they have to be processed positionally (or use inputobject hashtable or a hashtable as the argument) which is not ideal because scriptblocks cannot use the param block to validate and assign the input.

I recommend adding a ParameterList argument that would take a hashtable in the same format used for splatting, and call _ps.AddParameters for that hashtable right after this code:

https://github.com/PaulHigin/PSThreadJob/blob/6f72128a9377e2c63667f69bff6dc66e85d2f5ae/PSThreadJob/PSThreadJob.cs#L1036-L1042

Alternatively ArgumentList could accept a hashtable or parameterset, but this may interfere with activities that actually want to pass those specific types, hence the recommended separate Parameter.

I'm willing to attempt a PR if there is interest.

Workarounds

Args Hashtable Parsing

Put as first line of script rather than a param block, however doesn't allow any sort of validation within the parameters themselves

        if ($args[0] -is [HashTable]) {
            $args.keys.foreach{
                Set-Variable -Name $PSItem -Value $args[$PSItem]
            }
        }

Positional Params

Add [Parameter(Position=x)] to each matching arg parameter and pass the args as an array rather than a hashtable (Position can also be implicit). Allows the scriptblock to still be used as a cmdlet (for testing, etc.) but makes the actual threadjob run less structured (since you have to get the parameter order exactly right and you have to make sure optional parameters are towards the end)

$myargs = @(
    'test1'
    'test2'
)

start-threadjob -argumentlist $myargs {
    param(
        [Parameter(Position=0)]$test1,
        [Parameter(Position=1)]$test2
    )
    "Test1: $test1"
    "Test2: $test2"
}