Share via


How to call Powershell script and pass parameters from C# windows form?

Question

Friday, May 8, 2020 7:44 AM

I want to call powershell script which accepts some parameters from c# windows form.

For Example :- I have a powershell script which accepts 2 parameters and i have a windows form with two textboxes and a submit button. I want to pass parameters to powershell script from these two textboxes, and when i press the submit button it will call the powershell script and run it on powershell terminal and also show result in powershell terminal window.

All replies (6)

Friday, May 8, 2020 7:52 AM

Use PowerShell Class


Friday, May 8, 2020 11:09 AM

that's i know, but how???


Friday, May 8, 2020 11:21 AM

For example, this test sets a given file to Read Only =>

string sPath = @"E:\Test\Text.txt";
string sValue = "$true"; 
using (var ps = PowerShell.Create())
{    
    string sCommand = string.Format(@"Set-ItemProperty -Path {0} -Name IsReadOnly -Value {1}", sPath, sValue);
    ps.AddScript(sCommand);
    Collection<PSObject> results = ps.Invoke();                   
}

Tuesday, May 12, 2020 3:32 AM

Hi hassaan443,
I viewed your description and made a code example to achieve it.
Please follow the steps:
1.You need to add an assembly that is one of a set we got with our install of PowerShell. You can find these assemblies at C:\Program Files\Reference Assemblies\Microsoft\WindowsPowerShell\v1.0
2. Right-click on your project and choose Add Reference, select the Browse tab and locate these assemblies .Then add a reference to the System.Management.Automation.dll
3.In my test, I create two methods:  RunScript and LoadScript.  RunScript is used to parse scripts and LoadScript is my helper function that will load the contents of a script file and return a string.
More details you can refer to this document.
Here is my code example:

private void button1_Click(object sender, EventArgs e)
{
    textBox1.Text = RunScript(LoadScript(@"C:\Users\Desktop\AddItUp.ps1"));
}
private string RunScript(string scriptText)
{
    // create Powershell runspace
    Runspace runspace = RunspaceFactory.CreateRunspace();

    // open it
    runspace.Open();

    // create a pipeline and feed it the script text
    Pipeline pipeline = runspace.CreatePipeline();
    pipeline.Commands.AddScript(scriptText);

    // add an extra command to transform the script output objects into nicely formatted strings
    // remove this line to get the actual objects that the script returns. For example, the script
    // "Get-Process" returns a collection of System.Diagnostics.Process instances.
    pipeline.Commands.Add("Out-String");
           
    

    // execute the script
    Collection<PSObject> results = pipeline.Invoke();

    // close the runspace
    runspace.Close();

    // convert the script result into a single string
    StringBuilder stringBuilder = new StringBuilder();
    foreach (PSObject obj in results)
    {
        stringBuilder.AppendLine(obj.ToString());
    }

    // return the results of the script that has
    // now been converted to text
    return stringBuilder.ToString();
}
private string LoadScript(string filename)
{
    try
    {
        // Create an instance of StreamReader to read from our file.
        // The using statement also closes the StreamReader.
        using (StreamReader sr = new StreamReader(filename))
        {

            // use a string builder to get all our lines from the file
            StringBuilder fileContents = new StringBuilder();

            // string to hold the current line
            string curLine;

            // loop through our file and read each line into our
            // stringbuilder as we go along
            while ((curLine = sr.ReadLine()) != null)
            {
                // read each line and MAKE SURE YOU ADD BACK THE
                // LINEFEED THAT IT THE ReadLine() METHOD STRIPS OFF
                fileContents.Append(curLine + "\n");
            }
            string s2 = textBox2.Text.ToString();
            string s3 = textBox3.Text.ToString();
            string re = "AddStuff " + s2 + " " + s3;
            fileContents.Append(re);
            // call RunScript and pass in our file contents
            // converted to a string
            return fileContents.ToString();
        }
    }
    catch (Exception e)
    {
        // Let the user know what went wrong.
        string errorText = "The file could not be read:";
        errorText += e.Message + "\n";
        return errorText;
    }

}

AddItUp.ps1

# begin

function AddStuff($x,$y)
{
   $x + $y
}

# end

The result:


Best Regards,
Daniel Zhang

MSDN Community Support
Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact [email protected].


Wednesday, May 13, 2020 9:54 AM

Hi hassaan443,
Has your problem been solved? If it is resolved, we suggest that you mark it as the answer. So it can help other people who have the same problem find a solution quickly. If not solved, what problem did you encounter?
Best Regards,
Daniel Zhang

MSDN Community Support
Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact [email protected].


Wednesday, May 13, 2020 10:41 AM

Here is working example for powershell script, that gives you ASCII code for char. Assuming you have richTextbox1 for showing output of the script and that you have button1 which you trigger it to run - here is the code:

        public void RunPowershell()
        {
            var ps1File = @"C:\asc.ps1";

            ProcessStartInfo startInfo = new ProcessStartInfo();
            startInfo.FileName = @"powershell.exe";
            startInfo.Arguments = $@"& '{ps1File}' f";
            startInfo.RedirectStandardOutput = true;
            startInfo.RedirectStandardError = true;
            startInfo.UseShellExecute = false;
            startInfo.CreateNoWindow = true;
            Process process = new Process();
            process.StartInfo = startInfo;
            process.Start();

            string output = process.StandardOutput.ReadToEnd();
            string errors = process.StandardError.ReadToEnd();

            richTextBox1.Text = $"Output: {output}{Environment.NewLine}Errors = {errors}";
        }

        private void button1_Click(object sender, EventArgs e)
        {
            RunPowershell();
        }
This will give ascii code for char 'f'.

Bellow is the PS script attached to example:

function Syntax {
    Write-Host
    Write-Host "Asc.ps1,  Version 1.00"
    Write-Host "Returns the numeric ASCII value for the specified character"
    Write-Host
    Write-Host "Usage:   " -NoNewline
    Write-Host "ASC.PS1  char" -ForegroundColor White
    Write-Host
    Write-Host "Returns: Numeric ASCII value of " -NoNewline
    Write-Host "char" -ForegroundColor White
    Write-Host
    Write-Host "Notes:   The ASCII value is written to Standard Output (usually the screen)"
    Write-Host "         as well as returned as `"errorlevel`""
    Write-Host "         If more than 1 character is passed on the command line, only the first"
    Write-Host "         character will be used, the remainder of the string will be ignored."
    Write-Host "         The `"errorlevel`" will equal the ASCII value, or 0 if no parameter"
    Write-Host "         was passed, or -1 in case of errors or for this help"
    Write-Host
    Write-Host "Credits: Code to pass exit code as `"errorlevel`" to the calling batch file"
    Write-Host "         or PowerShell script by Serge van den Oever:"
    Write-Host "         weblogs.asp.net/soever/returning-an-exit-code-from-a-powershell-script" -ForegroundColor DarkGray
    Write-Host
    Write-Host "Written by Rob van der Woude"
    Write-Host "http://www.robvanderwoude.com"

    $Host.SetShouldExit( -1 )
    Exit
}

if ( $args.Length -eq 1 ) {
    if ( $args[0] -eq "/?" ) {
        Syntax
    } else {
        $input = $args[0]
    }
} else {
    Syntax
}

if ( $input -eq "" ) { $input = [string][char]0 }

[char]$char = $input[0]

Write-Host ([byte]$char) -NoNewline

# Pass exit code to calling batch or PowerShell script, by Serge van den Oever
# https://weblogs.asp.net/soever/returning-an-exit-code-from-a-powershell-script
$Host.SetShouldExit( [byte]$char )
Exit
Save it to disk C, call it asc.ps1 --> and you have working example.