你为什么不为你的主脚本使用一个配置文件,明确地告诉你要调用什么脚本和函数?像这样的东西(警告:这是从我写的东西中复制/粘贴和改编的代码。可能包含一些小故障,但这会给你一个大致的想法):
<?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