Search code examples
c#web-servicespowershellwebserverasmx

how to run a powershell script file from a webservice


I've created a web service and I'm wanting to run a powershell script from the webservice. I've stored the .ps1 file on the c:\ of the server that the web service is stored. When I call the webservice I get an error saying " the term --name of method-- is not recognized as the name of a cmdlet, function, script file,or operable program.

When i call the webservice from the server it is on it works fine.

Here is my method:

[WebMethod]
public void RunUserProfileSync(string scriptText)
{
    RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();

    Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
    runspace.Open();

    RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);

    Pipeline pipeline = runspace.CreatePipeline();
    pipeline.Commands.Add(scriptText);

    // Execute PowerShell script
    pipeline.Invoke();
}

so, when calling the webmethod I place "c:\nameoffile.ps1" in the parameters.

What should I do to correct this?


Solution

  • You should use the AddScript method instead of the Add method. Right now it's trying to look for a single command while your script probably has multiple commands.

    EDIT: You could also try reading the contents of the file and then passing it to AddScript.