Powershell "plugin"系统

标签 powershell

我们编写了一个 powershell 脚本,用于处理来自内部系统的图像并将其发送到另一个系统。现在,业务的另一部分希望加入其中,对数据进行自己的处理,并将其推送到另一个系统。打听了一下,公司周围有几个感兴趣的团体,所以我想让添加这些新系统变得简单。

第一个简单的原型(prototype)打开文件夹中的所有 .ps1 文件,并在其中运行一个专门命名的函数,基本上希望能得到最好的结果。不过,这似乎还可以改进。是否有一些既定的 powershell 最佳实践来制作一些类似插件的系统?如果没有,考虑到这是在一个非常安全的环境中执行的,并且新模块将由管理员 checkin ,我的上述方法是否有任何问题?

最佳答案

为什么不为主脚本使用配置文件,明确告诉要调用哪个脚本和哪个函数?像这样的东西(警告:这是从我写的东西中复制/粘贴和改编的代码。可能包含一些小故障,但这给了你总体思路):

<?xml version="1.0"?>
<configuration>
  <Plugins>
    <Plugin Path="c:\blah\plugin1.ps1" PowerShellFunction="My-Plugin-Function" />
  </Plugins>
</configuration>

在你的主脚本中:

function Load-Plugins
{
    param (
        [parameter(Mandatory = $true)][xml] $config,
        [parameter(Mandatory = $true)][string] $nodeType
    )

    $plugins = @{}

    foreach ($pluginNode in $config.SelectNodes($nodeType))
    {
        if ($pluginNode)
        {
            $Path = $pluginNode.Path
            $powerShellFunction = $pluginNode.PowerShellFunction

            $plugin = New-Object Object |
                Add-Member -MemberType NoteProperty -Name "Path" -Value $Path -PassThru |
                Add-Member -MemberType NoteProperty -Name "PowerShellFunction" -Value $powerShellFunction -PassThru

            $plugins[$Path] = $plugin
        }
    }

    return $plugins
}


function Execute-Plugins
{
    param (
        [parameter(Mandatory = $true)][hashtable] $plugins
    )

    $Error.Clear()

    if (!$plugins.Values)
        { return }

    foreach ($plugin in $plugins.Values)
    {
        & .\$plugin.Path
        Invoke-Expression "$($plugin.PowerShellFunction)"
    }
}


function Load-Script-Config  
{
    param (
        [parameter(Mandatory = $false)][string] $configFile
    )

    if (!$configFile)
        { $configFile = (Get-PSCallStack)[1].Location.Split(':')[0].Replace(".ps1", ".config") }

        return [xml](Get-Content $configFile)
}

$pluginConfig = Load-Script-Config
$plugins = Load-Plugins $config "configuration/Plugins/Plugin"
Execute-Plugins $plugins

关于Powershell "plugin"系统,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10504867/

相关文章:

powershell - 如何在Powershell中添加该程序集并使用其功能?

powershell - 删除字符串不同部分的唯一字符

sql-server - 从 PowerShell 访问 SQL Server 时出现问题

powershell - Azure - 及时访问您不拥有的订阅中的虚拟机

powershell - 使用PowerShell在路径开头添加file://

powershell - 如何使Powershell运行批处理文件然后保持打开状态?

oop - PowerShell - 如何添加私有(private)成员?

powershell - 从单行文本中过滤多个值

powershell - 通过Power Shell检索SSIS 2012 environmentvariable.name

powershell - 如何使用Get-ChildItem在具有特定名称的目录中查找文件?