C#中调用PowerShell代码

在C#中调用PowerShell代码,很多时候Add是不好使的!要用AddScript!记录一下!

        using (Runspace runspace = RunspaceFactory.CreateRunspace())
            {
                try
                {
                    runspace.Open();
                    Pipeline pipeline = runspace.CreatePipeline();
                    //必须要用AddScript。
                    pipeline.Commands.AddScript("Add-PSSnapin Microsoft.SharePoint.PowerShell");
                    pipeline.Commands.AddScript("$webApplications = Get-SPWebApplication");
                    pipeline.Commands.AddScript("$webApplicationUrls = $webApplications.url");
                    pipeline.Commands.AddScript("Get-SPWebApplication");
                    Collection<PSObject> results = pipeline.Invoke();
                    foreach (PSObject result in results)
                    {
                        MessageBox.Show(result.ToString());
                    }
                }
                catch (Exception ex) 
                {
                    MessageBox.Show(ex.ToString());
                }
            }

 

posted @ 2015-04-28 09:02  天外归云  阅读(899)  评论(0编辑  收藏  举报