问题描述
我们希望在数据库中存储和管理 PowerShell 脚本,并通过 C# 执行它们.我们如何在执行之前发现这样一个脚本的参数?因此我们可以将它们设置为已知值或提示用户输入值.
We want to store and manage PowerShell scripts in a database an execute them via C#.How can we discover the parameters of such a script before executing it? so we can set them to known values or prompt a user for values.
一些说明:
我们创建了一个管理系统 MS.
We create a management system MS.
- 管理员将 PowerShell 脚本存储在 MS 数据库中.
- 后来另一个管理员从 MS 提供的列表中选择了这个脚本.
- MS 发现脚本的参数.
- MS 提示管理员输入值.
MS 使用提供的参数执行脚本.
- An admin stores a PowerShell script in the MS database.
- Later a different admin selects this script from a list offered by the MS.
- MS discovers the parameters of the script.
- MS prompts the admin for values.
MS executes the script with the parameters supplied.
string testScript = @"
{
param(
[ValidateNotNullOrEmpty()]
[string]$Name
)
get-process $name
";
Dictionary<string,object> DiscoverParameters()
{
using (PowerShell psi = PowerShell.Create())
{
psi.AddScript(testScript);
var pars = new Dictionary<string,object>();
//How do we get at the parameters
return pars;
}
}
void ExecuteScript(Dictionary<string,object> pars)
{
using (PowerShell psi = PowerShell.Create())
{
psi.AddScript(testScript);
pars.ToList().ForEach(p => psi.AddParameter(p.Key, p.Value));
Collection<PSObject> PSOutput = psi.Invoke();
//...
}
}
推荐答案
mjolinor 是正确的,使用 PowerShell 解析器可能是获取参数的最佳方式.该示例在 PowerShell 中,下面是在 C# 中的示例.我不太确定你在寻找什么,参数是 Dictionary
.在这里,我们只是将名称粘贴到列表中,尽管您可以提取其他信息,例如静态类型.
mjolinor is correct that using the PowerShell parser is probably the best way to get the parameters. That example is in PowerShell, below is an example in C#. I'm not quite sure what you are looking for with the parameters being Dictionary<string, object>
. Here we just stick the names into the list although there is other info you could pull out like the static type.
using System.Management.Automation;
using System.Management.Automation.Language;
static void Main(string[] args)
{
const string testScript = @"
param(
[ValidateNotNullOrEmpty()]
[string]$Name
)
get-process $name
";
foreach(var parameter in GetScriptParameters(testScript))
{
Console.WriteLine(parameter);
}
}
private static List<string> GetScriptParameters(string script)
{
Token[] tokens;
ParseError[] errors;
var ast = Parser.ParseInput(script, out tokens, out errors);
if (errors.Length != 0)
{
Console.WriteLine("Errors: {0}", errors.Length);
foreach (var error in errors)
{
Console.WriteLine(error);
}
return null;
}
return ast.ParamBlock.Parameters.Select(p => p.Name.ToString()).ToList();
}
这篇关于如何在 C# 中发现 PowerShell 脚本参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!