使用要添加引用System.Management.Automation.dll; 此DLL在C:\Program Files (x86)\Reference Assemblies\Microsoft\WindowsPowerShell\v1.0
private static string RunScript(string scriptText)
{
// create Powershell runspace
Runspace runspace = RunspaceFactory.CreateRunspace();
// open it
runspace.Open();
// create a pipeline and feed it the script text
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript(scriptText);
pipeline.Commands.Add("Out-String");
// execute the script
Collection<PSObject> results = pipeline.Invoke();
// close the runspace
runspace.Close();
// convert the script result into a single string
StringBuilder stringBuilder = new StringBuilder();
foreach (PSObject obj in results)
{
stringBuilder.AppendLine(obj.ToString());
}
return stringBuilder.ToString();
}
public void RunScript(List<string> scripts)
{
try
{
Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
Pipeline pipeline = runspace.CreatePipeline();
foreach (var scr in scripts)
{
pipeline.Commands.AddScript(scr);
}
//返回结果
var results = pipeline.Invoke();
runspace.Close();
}
catch (Exception e)
{
Log.WriteLog(DateTime.Now.ToString() + "日志记录:执行ps命令异常:" + e.Message);
}
}
C# 调用powershell 执行命令
最新推荐文章于 2022-12-01 19:30:00 发布