在.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(); }