我可以覆盖 Powershell 本机 cmdlet 但从我的覆盖中调用它吗 [英] Can I override a Powershell native cmdlet but call it from my override

查看:41
本文介绍了我可以覆盖 Powershell 本机 cmdlet 但从我的覆盖中调用它吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为在 Javascript 中可以这样做.在 Powershell 中,我不知道如何:

假设我想用我的自定义方法覆盖对 write-host 的每个调用,但有时我想在我的覆盖中执行本机 write-host.是否可以将本机实现存储在另一个名称下,以便以后从新实现中调用它?

更新:在我看来,答案

请注意,如果您将其保存在配置文件或类似性质的内容中,请不要忘记您已完成此操作.如有疑问,请使用 Get-Command Write-Host.在我的情况下,您可以通过调用 Remove-Item function:write-host

来删除覆盖

您还可以查看所谓的代理功能,但我认为这对于您打算做的事情来说太过分了.

In Javascript it is possible to do so, I think. In Powershell I'm not sure how to :

Let's say I want to override every call to write-host with my custom method but at some time I want to execute the native write-host inside my overide. Is it possible to store the native implentation under another name so as to call it later from new implementation ?

Update : it seems to me that the answer https://serverfault.com/a/642299/236470 does not fully answer the second part of my question. How do I store and call the native implementation ?

解决方案

Calls to functions will override cmdlets. You can read more on this from about_Command_Precedence on TechNet ...

If you do not specify a path, Windows PowerShell uses the following precedence order when it runs commands:

  1. Alias
  2. Function
  3. Cmdlet
  4. Native Windows commands

So simply making a function of the same name as a native cmdlet will get you what you want.

function Write-Host{
    [cmdletbinding()]
    param(
        [Parameter(Mandatory,ValueFromPipeline)]
        $string
    )
    Process {
        # Executes once for each pipeline object
        If ($string -match "bagels"){
            Microsoft.PowerShell.Utility\Write-Host $string -ForegroundColor Green
        }else{
            Microsoft.PowerShell.Utility\Write-Host $string
        }
    }
}

So now write-host works with pipeline input that we can filter with. Calling the "real" cmdlet is as easy as specifying the module in the call. You can see I have done that twice in the above code sample. Some sample usage and output would be the following:

Be careful that you don't forget you have done this if you save it in a profile or something of that nature. Use Get-Command Write-Host whenever in doubt. In my case you can remove the override by calling Remove-Item function:write-host

You can also look into what are called proxy functions but I think that is overkill for what you intend to do.

这篇关于我可以覆盖 Powershell 本机 cmdlet 但从我的覆盖中调用它吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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