通过C#代码执行PowerShell命令

3

我希望通过C#代码向Powershell命令或脚本(哪个是正确的?)添加变量声明,并将默认值存储在C#变量中。例如,在Powershell中,我输入以下行:

 $user = 'Admin'

我想在C#代码中添加这行。

powershell.AddScript(String.Format("$user = \"{0}\"", userName));

或者

powershell.AddCommand(String.Format("$user = \"{0}\"", userName));

我尝试使用AddCommand(),但它抛出异常。我使用的是PS 2.0。


1
你应该使用 AddScript 方法,不是吗? - BartekB
1个回答

4
根据这篇文章 如何从C#运行PowerShell脚本,你需要类似下面的东西:
// create Powershell runspace
Runspace runspace = RunspaceFactory.CreateRunspace();
// open it
runspace.Open();

Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript(String.Format("$user = \"{0}\"", userName));
pipeline.Commands.AddScript("#your main script");

// execute the script
Collection<psobject> results = pipeline.Invoke();
// close the runspace
runspace.Close();

请查看此处关于在Stackoverflow上从C#应用程序中运行Powershell脚本的问题:Run Powershell-Script from C# Application


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接