How to run a powershell script from a win form written in C#

前端 未结 2 1379
情话喂你
情话喂你 2021-01-15 18:03

first of all, I\'ve got a bit of development skills but it\'s been ages since i\'ve use them. Now i\'m trying to automate an install for a server application. So what i\'m t

2条回答
  •  执笔经年
    2021-01-15 18:38

    Add Reference : System.Management.Automation

    Using System.Collections.Objectmodel and using System.Management.Automation

    using (PowerShell PowerShellInstance = PowerShell.Create())
                {
                    // use "AddScript" to add the contents of a script file to the end of the execution pipeline.
                    // use "AddCommand" to add individual commands/cmdlets to the end of the execution pipeline.
                    PowerShellInstance.AddScript("param($urlPath) New-Item -ItemType directory -Path \"$urlPath$d\";");
    
                    // use "AddParameter" to add a single parameter to the last command/script on the pipeline.
                    PowerShellInstance.AddParameter("urlPath", @"D:\New PS Folder\");
                    Collection PSOutput = PowerShellInstance.Invoke();
    
                    // loop through each output object item
                    foreach (PSObject outputItem in PSOutput)
                    {
                        // if null object was dumped to the pipeline during the script then a null
                        // object may be present here. check for null to prevent potential NRE.
                        if (outputItem != null)
                        {
                            //TODO: do something with the output item 
                            // outputItem.BaseOBject
                            MessageBox.Show(outputItem.Properties.ToString());
                        }
                    }
                }
    

提交回复
热议问题