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

前端 未结 2 1380
情话喂你
情话喂你 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<PSObject> 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());
                        }
                    }
                }
    
    0 讨论(0)
  • 2021-01-15 18:40

    I think you need to use "PowerShellInstance.Invoke();"

    Microsoft has a great tutorial here. https://blogs.msdn.microsoft.com/kebab/2014/04/28/executing-powershell-scripts-from-c/

    0 讨论(0)
提交回复
热议问题