gpt4 book ai didi

Powershell "plugin"系统

转载 作者:行者123 更新时间:2023-12-02 08:03:12 25 4
gpt4 key购买 nike

我们编写了一个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com