有没有办法在Powershell中为对象方法创建别名? [英] Is there a way to create aliases for object methods in powershell?

查看:79
本文介绍了有没有办法在Powershell中为对象方法创建别名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现在某些情况下执行上下文很重要时,我会在Powershell脚本中重复我自己.延迟的字符串扩展就是这种情况之一:

I'm finding that I am repeating myself in powershell scripts in some cases where execution context matters. Delayed string expansion is one such case:

$MyString = 'The $animal says $sound.'

function MakeNoise{ 
   param($animal, $sound)
   $ExecutionContext.InvokeCommand.ExpandString($MyString)
}

PS> MakeNoise pig oink
The pig says oink.

那条长长的ExpandString()行经常被重复.我希望该行简洁明了:

That long ExpandString() line gets repeated frequently. I'd prefer that line to be terse like this:

xs($MyString)
xs $MyString
$MyString | xs

其中任何一个都是可取的.在这种情况下,我通常在小命令中封装的策略似乎不起作用,因为对ExpandString()的调用上下文很关键.

Any of these would be preferable. My usual strategies of encapsulation in commandlets don't seem to work for this case because the context of the call to ExpandString() is critical.

所以我的问题是:

  1. 是否可以为对象方法创建别名?
  2. 在保留调用上下文的同时,还有其他方法可以简洁地调用对象的方法吗?

推荐答案

似乎您需要一种方法来延迟对$ ExecutionContext的求值,直到实际进行字符串扩展为止.这是通过功能实现的一种方法:

It seems you need a way to delay evaluating $ExecutionContext until it's time to actually do the string expansion. Here's one way to do that, implemented as a function:

function xs
{
    [CmdletBinding()]
    param
    (
        [parameter(ValueFromPipeline=$true,
                   Position=0,
                   Mandatory=$true)]
        [string]
        $string
    )
    process
    {
        $code = "`$ExecutionContext.InvokeCommand.ExpandString(`"$string`")"
        [scriptblock]::create($code) 
    }
}

然后:

&($MyString | xs)
&(xs $MyString)

脚本块是在运行时创建的,因此每次调用都会评估$ ExecutionContext.

The scriptblock is created at runtime, so $ExecutionContext is evaluated for each invocation.

这篇关于有没有办法在Powershell中为对象方法创建别名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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