可以使用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,實現更靈活和強大的功能。