在 Windows Server 上,PowerShell 是個好用的指令工具,可以省去不少人工作業。而筆者最近遇到需要因應網站的狀況去執行特定的 PowerShell 指令,這部份就需要寫 C# 程式做為輔助,本篇文章將會介紹如何在 C# 寫的 Console 程式中執行指令。

首先在 Nuget 管理工具新增下列有關 PowerShell 的套件:

然後新增一個呼叫指令的程式碼(範例為管理 IIS 的指令):

using (PowerShell powershell = PowerShell.Create())
{
    powershell.AddScript("Set-ExecutionPolicy RemoteSigned;");
    powershell.AddScript("Import-Module WebAdministration;");

    powershell.AddScript("Start-WebSite -Name 'TestWebSite';");
    powershell.AddScript("Start-WebAppPool -Name 'TestWebSite';");
    powershell.AddScript("Start-WebAppPool -Name 'TestWebSite';");
    powershell.AddScript("Start-WebSite -Name 'TestWebSite';");

    foreach (PSObject result in powershell.Invoke())
    {
        Console.WriteLine(result);
    }
    string message = $"already restrt web site.";
    Console.WriteLine($"{DateTime.Now.ToString()}: {message}");
}

然後記得更改下列設定,將程式設為64位元:

參考資料