1. 程式人生 > 實用技巧 >.net 中呼叫powershell 方法

.net 中呼叫powershell 方法

在.net 環境下呼叫powershell 指令碼,需要額外引用 “System.Management.Automation;"

powershell 指令碼示例,檔名儲存為 2.ps1:

#檢查IIS狀態
  function  Get-IISStatus
  {
  param(
    #輸入引數
    #[Paramter(Mandatory=$true)]
    [String]
    $password,
    [String]
    $username,    
    $server
    )
    $password_conv =ConvertTo-SecureString -String $password
-AsPlainText -Force #建立憑證,server 2012及以上版本可用,2008似乎不行 $credential =New-Object System.Management.Automation.PSCredential -argumentlist $username ,$password_conv $sessions=New-PSSession -ComputerName $server -credential $credential #遠端執行指令碼,加了過濾 #Invoke-Command -Session $sessions -ScriptBlock {Get-WebAppPoolState -Name 'DefaultAppPool' | % { return @{($_.itemxpath -split ("'"))[1]="$($_.value)" } } }
#未過濾返回值 Invoke-Command -Session $sessions -ScriptBlock {Get-WebAppPoolState -Name 'DefaultAppPool'} }

對應.net 中呼叫程式碼示例:

            //獲取SP1檔案來執行指令碼
            string filePath = Server.MapPath("../Scripts/Powershell/2.ps1");
            try
            {
                using (Runspace runspace = RunspaceFactory.CreateRunspace())
                {

                    
string te = GetFileContent(filePath); runspace.Open(); PowerShell ps = PowerShell.Create(); ps.Runspace = runspace; ps.AddScript(te); ps.Invoke();//呼叫指令碼 //執行指令碼中的方法,附帶引數 ps.AddCommand("Get-IISStatus").AddParameters( new Dictionary<string, string>() { { "password","123" }, { "username", "username"},
                             { "server", "server1"}
                             }
                       );
                    //獲取返回值
                    foreach (PSObject result in ps.Invoke())
                    {
                        if (result.Properties["Name"].Value.ToString() == "state" & result.Properties["Value"].Value.ToString() == "Stopped")
                        {
                            Console.Write("IISpool 已經關閉!");
                        }
                        else
                        {
                            Console.Write("有問題?!");
                        }

                    }


                    return null;
                }
            }
            catch (Exception ex)
            {

                throw;
            }

 private static string GetFileContent(string filePath)
        {
            FileStream fs = new FileStream(filePath, FileMode.Open);
            StreamReader reader = new StreamReader(fs);
            return reader.ReadToEnd();
        }