Click here to Skip to main content
15,887,776 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi.

I am having trouble running a powershell script saved in another server.
I need to execute the powershell script by C#.
Server 1 is where the C# program is saved
Server 2 is where the powershell script is saved.

Here is my c# method

where variable serviceList is the parameter/argument to be passed to the powershell script.

variable psPath will contain the string like "\\[serveripaddress]\g$\adminscripts\dotalltool_scripts\stopservice.ps1

public string runScriptPS(string serviceList, string operation)
        {
            string psFileName = operation == "Stop" ? "stopservice.ps1" : operation == "Start" ? "startservice.ps1" : "restartservice.ps1";
            string server = hdnServerSelected.Value;
            string psPath = @"\\" + server + @"\g$\AdminScripts\dotalltool_scripts\" + psFileName;
            string paramSapArray = (char)34 + serviceList + (char)34;
         


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

            RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);
            Pipeline pipeline = runspace.CreatePipeline();
            Command psCmd = new Command(psPath);
            CommandParameter sapParam = new CommandParameter("SAPArray", paramSapArray);
            psCmd.Parameters.Add(sapParam);
            pipeline.Commands.Add(psCmd);

            Collection<PSObject> results = pipeline.Invoke("Set-ExecutionPolicy Unrestricted");

            

            StringBuilder sb = new StringBuilder();
            foreach (PSObject obj in results)
            {
                sb.AppendLine(obj.ToString());
            }
            string a = sb.ToString();
            return sb.ToString();
        }



Here is the error that I am getting

File \\serveripaddress\g$\AdminScripts\dotalltool_scripts\stopservice.ps1 cannot be loaded. The file \\serveripaddress\g$\AdminScripts\dotalltool_scripts\stopservice.ps1 is not digitally signed. You cannot run this script on the current system. For more information about running scripts and setting execution policy, see about_Execution_Policies at http://go.microsoft.com/fwlink/?LinkID=135170.]


What I have tried:

I already indicated execution policy on the pipeline.Invoke()
Posted
Updated 18-Nov-19 1:45am

1 solution

See CodeProject article here: Enable Remote PowerShell Execution in C#[^]

You may also be interested in: Running PSexec in Multi Thread using Powershell[^]
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900