首页 > Web开发 > 详细

.net 中调用powershell 方法

时间:2020-07-14 14:44:06      阅读:56      评论:0      收藏:0      [点我收藏+]

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

 

.net 中调用powershell 方法

原文:https://www.cnblogs.com/daniel-niu/p/13298536.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!