1

I have the following Powershell script :

   param(
    [string] $Source ,
    [string] $Target ,
    [string] $UserId  
)
Set-Location "C:\My folder"
& "C:\Program Files\nodejs\node.exe" "index.js" $Source $Target $UserId

I need to execute it from a C# application, so I have this code:

var process = new Process();
string parameters = string.Format(" -Source {0} -Target {1} -UserId {2} ", Source, Target, UserName);
process.StartInfo.FileName = @"C:\windows\system32\windowspowershell\v1.0\powershell.exe";
process.StartInfo.Arguments = "\"&'" + ScriptName + "'\" ";
process.Start();
string s = process.StandardOutput.ReadToEnd();
process.WaitForExit();

This works in invoke my script, but I don't know how to pass the parameters that I have in the variables.

I already tried using Runspace runspace = RunspaceFactory.CreateRunspace(); but this way doesn't execute my script.

5
  • Did you find this during your searching for a solution: stackoverflow.com/questions/10260597/… Commented Jun 9, 2021 at 22:12
  • Yes, I tried that exactly piece of code, and did'nt work. just do not execute my script file. Like nothing happens... Commented Jun 9, 2021 at 22:14
  • If I type this at the CMD command line: C:\windows\system32\windowspowershell\v1.0\powershell.exe -command "get-date -year 2010" then Powershell starts up and runs get-date -year 2010. Try something like that. I.E., set the arguments to -command "get-date -year 2010" (substituting your script and your script arguments) Commented Jun 9, 2021 at 22:33
  • Where do you declare ScriptName? Also, the argument line is unclear... Check out this article on how to call the exe:learn.microsoft.com/en-us/powershell/module/… Commented Jun 9, 2021 at 22:35
  • Oh, sure. I declared that variable a little before that piece of code. Like this: string ScriptName = "c:\\code\\MyFolder\\data\\script\\StepOne.ps1"; and, I need the C# code to pass the parameters, not the powershell script, because I already have that. Commented Jun 9, 2021 at 22:39

1 Answer 1

0

Assuming that you can use C# v6+ interpolated strings, and assuming that the arguments you're trying to pass to script ScriptName are stored in variables Source, Target, and UserId:

process.StartInfo.Arguments = $"-File \"{ScriptName}\" \"{Source}\" \"{Target}\" \"{UserId}\"";
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.