daniyalahmad
daniyalahmad

Reputation: 3843

C# Stop-Process command of PowerShell

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();
    }  

Upvotes: 0

Views: 1965

Answers (2)

Keith Hill
Keith Hill

Reputation: 201692

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.

Upvotes: 2

therealtbs
therealtbs

Reputation: 162

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

Upvotes: 2

Related Questions