可以使用C#代码来调用PowerShell脚本或命令,实现两者的集成。以下是一种常见的方法:
using System;
using System.Diagnostics;
class Program
{
static void Main()
{
using (Process process = new Process())
{
process.StartInfo.FileName = "powershell.exe";
// 指定要执行的PowerShell脚本或命令
process.StartInfo.Arguments = "-ExecutionPolicy Bypass -File C:\\Path\\To\\Script.ps1";
process.Start();
process.WaitForExit();
}
}
}
using System;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
class Program
{
static void Main()
{
using (Runspace runspace = RunspaceFactory.CreateRunspace())
{
runspace.Open();
using (Pipeline pipeline = runspace.CreatePipeline())
{
// 执行PowerShell脚本或命令
pipeline.Commands.AddScript("Get-Process");
pipeline.Commands.Add("Out-String");
Collection<PSObject> results = pipeline.Invoke();
foreach (PSObject obj in results)
{
Console.WriteLine(obj.ToString());
}
}
}
}
}
通过上述方法,可以在C#代码中轻松集成PowerShell,实现更灵活和强大的功能。