0

I want to use Stop-Process command (of PowerShell) in c#. I know how to use "Get-Process" command, But in the case of stop-process we have to give arguments(process name). In my case I am taking arguments from user in textbox.

   private void button2_Click(object sender, EventArgs e)
    {
        PowerShell ps = PowerShell.Create();

        ps.AddCommand("Stop-Process -Name " + (textBox1.Text).ToString());


        ps.Invoke();
    }  
2
  • What is the problem here? Do you get any errors or is anything behaving unexpected? Commented Nov 9, 2013 at 20:32
  • Yeah, Actually it's run time error : The term 'Stop-Process -Name ' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. Commented Nov 9, 2013 at 20:35

2 Answers 2

2

You have to add the argument seperately:

private void button2_Click(object sender, EventArgs e)
{
    PowerShell ps = PowerShell.Create();

    ps.AddCommand("Stop-Process");
    ps.AddParameter("Name", textBox1.Text);

    ps.Invoke();
} 

Also you don't have to do textBox1.Text.ToString() because the text property is already a string

Sign up to request clarification or add additional context in comments.

4 Comments

Not Working :/ It still giving me Error : The term 'Stop-Process -Name notepad' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
I have missed a space in my initial edit, try it with this code now.
I hope you have a good reason to use Powershell, because it would be faster and easier using the System.Diagnostics.Process class.
That is weird, it seems to work for me just fine. Does your code look like mine?
2

Try this:

ps.AddCommand("Stop-Process").AddParameter("Name", textBox1.Text);

You could use your original approach if you used AddScript instead:

ps.AddScript("Stop-Process -Name " + textBox1.Text); # Not recommended

However I would not recommend this approach because it opens up your script to injection attacks similar to SQL injection. What if someone types into the text box: "notepad; Remove-Item C:\ -r -force"? :-)

That said, even with the first approach you should check the user input to make sure folks are somewhat limited in the processes they can shut down. If they type in "svchost", they might have a bad day as their system becomes unstable.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.