执行内置cmdlet后,有条件地执行自定义PowerShell函数/ cmdlet

时间:2018-03-22 23:09:12

标签: powershell automation powercli

每次用户执行特定的内置cmdlet时,如何设置要运行的自定义函数(导入所述函数的模块时)?

e.g。如果用户加载了包含自定义函数的自定义模块并运行“Get-Process”cmdlet,则在输出返回到控制台后,将自动调用并执行“Run-CustomFunction”。

----------- -----------编辑

这是一个简单的函数,它根据用户输入读取.csv,并使用正则表达式构造cmd行,并由一个流行的软件供应商执行带有模块参数的函数。几乎像一个啪啪声。它有一个姐妹功能,可以帮助用户跟踪控制台标题栏中的使用情况。我想要解决的是,当用户输入cmd行时,控制台的标题栏不会更新。 .csv经常被操纵,因此有时需要的值不可用,用户必须手动键入cmdlet和参数值。手动键入时,我仍然希望更新标题栏。

1 个答案:

答案 0 :(得分:0)

Here is one possibility, though I'm not sure I'd actually recommend it:

In your custom module, re-define the cmdlet you want to modify so that it calls the original cmdlet, then does whatever extra stuff you want. For example, here is how we could make Get-Service run after every call to Get-Process:

# Define a function called Get-Process
function Get-Process
{
    # Call original Get-Process cmdlet using 'modulename\cmdletname' syntax
    Microsoft.PowerShell.Management\Get-Process | Out-Host

    # Call get service (could be your own function instead)
    Get-Service
}

So, the output of the original Get-Process goes to the console and the result of Get-Service is returned from the function (and also goes to the console by default. There are many reasons this is a very bad idea (e.g. it will break anything that expects the default behaviour from Get-Process), but you can try it if you want.