Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

powershell - How to create a wrapper for an advanced function cmdlet that uses dynamic parameters

I'm trying to create a wrapper (proxy) for Pester's Should cmdlet. Possible use cases include transparent logging of test input even in case of success and improve the way Pester logs objects of certain types, e. g. hashtable.

As Should is an advanced function, forwarding arguments via $args splatting does not work.

So I tried to generate a wrapper using System.Management.Automation.ProxyCommand::Create(), as described by this answer:

$cmd = Get-Command Should
$wrapperSource = [System.Management.Automation.ProxyCommand]::Create( $cmd )
$wrapperSource >should_wrapper.ps1

When calling the wrapper, Powershell outputs this error message:

Should: Parameter set cannot be resolved using the specified named parameters. One or more parameters issued cannot be used together or an insufficient number of parameters were provided.

It looks like the wrapper generator doesn't understand the dynamicparam declaration of Should.

How to write a generic wrapper for Pester's Should without duplicating Pester code?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It looks like the wrapper generator doesn't understand the dynamicparam declaration of Should.

The wrapper generator omits dynamicparam by default. Fortunately, this is easily fixed with a bit of templating:

$cmd = Get-Command Should
$pct = [System.Management.Automation.ProxyCommand]
$wrapperSource = @(
  $pct::GetCmdletBindingAttribute($cmd)
  'param('
    $pct::GetParamBlock($cmd)
  ')'
  'dynamicparam {'
    $pct::GetDynamicParam($cmd)
  '}'
  'begin {'
    $pct::GetBegin($cmd)
  '}'
  'process {'
    $pct::GetProcess($cmd)
  '}'
  'end {'
    $pct::GetEnd($cmd)
  '}'
) -join [Environment]::NewLine

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...