如何为使用动态参数的高级函数 cmdlet 创建包装器 [英] How to create a wrapper for an advanced function cmdlet that uses dynamic parameters

查看:60
本文介绍了如何为使用动态参数的高级函数 cmdlet 创建包装器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为 Pester 的应该创建一个包装器(代理) cmdlet.可能的用例包括即使成功也能透明记录测试输入改进 Pester 记录某些类型对象的方式,例如.G.hashtable.

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.

由于 Should 是一个高级函数,通过 $args splatting 转发参数不起作用.

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

所以我尝试使用 System.Management.Automation.ProxyCommand::Create() 生成包装器,如 这个答案:

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

调用包装器时,Powershell 输出此错误消息:

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.

看起来包装器生成器不理解 Should 的动态参数声明.

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

如何在不复制 Pester 代码的情况下为 Pester 的 Should 编写通用包装器?

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

推荐答案

看起来包装器生成器不理解 Should 的 dynamicparam 声明.

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

包装器生成器省略 dynamicparam 默认情况下.幸运的是,这可以通过一些模板轻松解决:

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

这篇关于如何为使用动态参数的高级函数 cmdlet 创建包装器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆