1

I have the following c# code:

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

var runSpaceInvoker = new RunspaceInvoke(runspace);
runSpaceInvoker.Invoke("Set-ExecutionPolicy Unrestricted");

// create a pipeline and feed it the script text
var pipeline = runspace.CreatePipeline();
var command = new Command(@". .\MyScript.ps1");
command.Parameters.Add("MyParam1", value1);
command.Parameters.Add("MyParam2", value2);
pipeline.Commands.Add(command);

pipeline.Invoke();
runspace.Close();

But I am getting the error Powershell ps1 file “is not recognized as a cmdlet, function, operable program, or script file.”

MyScript.ps1 is copied to the bin folder so it is at the same level as the running program.

I found this Powershell ps1 file "is not recognized as a cmdlet, function, operable program, or script file."

But it did not solve the problem. Any idea what else could cause this error?

doorman
  • 15,707
  • 22
  • 80
  • 145

1 Answers1

1

Problem is likely that your application inherits its working directory from the parent process, so you can't predict that . refers to the directory in which the executable resides.

You could construct the full path to the script with something like:

using System.Reflection;
using System.IO;

// ...

string exePath = Assembly.GetExecutingAssembly().Location;
string exeFolder = Path.GetDirectoryName(exePath);

string scriptPath = Path.Combine(exeFolder,"MyScript.ps1");

var command = new Command(". " + scriptPath);
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206
  • Hi Mathias, I used your code but I still get the exception {"The term '. C:\\ProjectFolder\\bin\\Debug\\MyScript.ps1' 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."} The path is correct and I can open the file. Any other idea why this could occur? – doorman Jan 10 '18 at 19:16
  • @doorman I had the same kind of problem but it was because we didn't escape the string for the other script properly. _i.e. you need_ `new Command(". '" + scriptPath + "'");` – icepicker May 13 '19 at 05:28