ChrisLupson
ChrisLupson

Reputation: 51

Running powershell in C#, not having much luck!

I have created a asp.net web application for internal use that allows certain users to start and stop Virtual machines that are linked to there QA testing environments, the code behind page runs a powershell script that starts the selected server once a button is pressed on an ASP.net page.

I have reserched and implimented alot of the code from this site but i am coming up against a few problems.

everytime i click the button on the main web page the error that is fed back from the powershell script says"You cannot call a method on a null-valued expression." the only problem is if i run it from a powershell prompt like this ". \script\test.ps1 'W7EA9'" it works fine.

This is the class that calls the powershell script.

    public String Startserver(String Servername)
    {

        String scriptText =". \\scripts\\test.ps1 " + Servername + "";


        // 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);


        // execute the script
        Collection<PSObject> results = new Collection<PSObject>();

        try
        {
            results = pipeline.Invoke();
        }
        catch (Exception ex)
        {
            results.Add(new PSObject((object)ex.Message));
        }

        // 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 stringBuilder.ToString();
        //return scriptText;
    }

and here is the powershell script it is trying to run

    Param ($server = $arg[0])

    $Core = get-wmiobject -namespace root\virtualization -class Msvm_Computersystem -filter "ElementName = '$server'"
    $status = $Core.RequestStateChange(2) `

It may be somthing really obvious but im just not seeing it and any help would be great.

thanks

Chris

Upvotes: 2

Views: 4531

Answers (5)

jbsmith
jbsmith

Reputation: 1666

In powershell, the default arguments collection is called $args, with an 's'; I'm pretty sure that's why $server is null when you run it via code, and thus the Get-WmiObject call returns null, causing the error when you attempt to call the RequestStateChange method on it.

I'm guessing it works fine in your normal powershell window because you already have a $server variable in the session.

Upvotes: 0

Greg Jacobs
Greg Jacobs

Reputation: 11

Below is how I ended up doing this.

Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
Pipeline pipeline = runspace.CreatePipeline();

Command myCommand = new Command("C:\\Scripts\\Test.ps1");
//I used full path name here, not sure if you have to or not 

CommandParameter myParam1 = new CommandParameter("-ServerName", "myServer");
myCommand.Parameters.Add(myParam1);
//You can add as many parameters as you need to here

pipeline.Commands.Add(myCommand);

Collection<PSObject> results = pipeline.Invoke();
runspace.Close();

StringBuilder stringBuilder = new StringBuilder()
foreach (PSObject obj in results) {
    stringBuilder.AppendLine(obj.ToString());
}
string thestring = stringBuilder.ToString();

A few notes. The scripts first line that is not a comment or blank line should be the parameter list formatted like this:

param([string]$ServerName,[string]$User)

You have this, I just wanted to acknowledge the fact that I could not get this working when my script file was a function with parameters.

For certain commands you may need additional privileges, in my case all of my scripts worked this way except for creating a mailbox for which I had to add credentials onto the connection.

Greg

Upvotes: 0

ravikanth
ravikanth

Reputation: 25840

Here is a best step-by-step guide to running PowerShell from ASP.NET.

http://devinfra-us.blogspot.com/2011/02/using-powershell-20-from-aspnet-part-1.html

HTH

Upvotes: 3

ChrisLupson
ChrisLupson

Reputation: 51

i am passing the paramater from a button press on an asp.net page the code behind looks like this

        Hypervserver Start = new Hypervserver();

        String result = Start.Startserver("W7EA9");

        Label1.Visible = true;
        Label1.Text = result;

Upvotes: 0

Mike Shepard
Mike Shepard

Reputation: 18186

I don't see where you're providing a parameter to the script anywhere.

Upvotes: 0

Related Questions