powershell - 我可以覆盖 Powershell native cmdlet 但从我的覆盖中调用它吗

标签 powershell

我认为在 Javascript 中可以这样做。在 Powershell 中,我不确定如何:

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

更新:在我看来答案 https://serverfault.com/a/642299/236470没有完全回答我问题的第二部分。如何存储和调用 native 实现?

最佳答案

对函数的调用将覆盖 cmdlet。您可以从 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


因此,只需创建一个与 native cmdlet 同名的函数即可获得您想要的。
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
        }
    }
}

所以现在write-host适用于我们可以过滤的管道输入。调用“真正的”cmdlet 就像在调用中指定模块一样简单。你可以看到我在上面的代码示例中做了两次。一些示例用法和输出如下:

enter image description here

如果您将其保存在配置文件或类似性质的东西中,请注意不要忘记您已经完成了此操作。使用Get-Command Write-Host每当有疑问。在我的情况下,您可以通过调用 Remove-Item function:write-host 来删除覆盖。

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

关于powershell - 我可以覆盖 Powershell native cmdlet 但从我的覆盖中调用它吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33747257/

相关文章:

powershell - 为什么脚本将自身输出到控制台?

powershell - 将桌面路径添加到 powershell 以轻松在文件夹之间切换?

powershell - 如何在 powershell 中找到 Windows 10 上的 Microsoft Edge 版本?

azure - 使用 REST API 运行 Azure DevOps 测试用例

arrays - Powershell 比较 2 个具有不同属性的数组

powershell - "get-wmiobject win32_process -computername"得到错误 "Access denied , code 0x80070005"

powershell - 在 Powershell 中使用加密密码作为 CMD 的参数

windows - 在 Powershell 中将 X 个文件从一个文件夹移动到另一个文件夹

arrays - 如何使用PSv2在PSobjects数组中搜索特定对象键

powershell - 代码块阻止脚本运行,但以交互方式运行