简体   繁体   中英

Passing and accessing Powershell parameters from C#

I am trying to pass parameters to Powershell script from a C# class. I am running the script using Process.Start .

string powerShellLocation = @"C:\WINDOWS\system32\windowspowershell\v1.0\powershell.exe";
ProcessStartInfo psi = new ProcessStartInfo(powerShellLocation);
psi.Arguments = String.Format("{0} {1}", scriptPath, "some_parameter");

The above does not work. Can someone please tell me how to achieve this?

You need to set the parameter name. Something like this should work:

string parameters = string.Format("-FILE {0} -parameter1 \"{1}\"", psFilePath, parameter1Value);
Process powershell = new Process()
{
     StartInfo = new ProcessStartInfo("powershell.exe", parameters)
      {
           UseShellExecute = false,
           RedirectStandardOutput = true,
           RedirectStandardError = true
      }
};

Did you set the execution policy to unrestricted or to something that allows you to execute the script. By default Powershell sets scripts to be unrestricted to prevent malicious scripts from running.

Run this command as an administrator when powershell is running:

Get-ExecutionPolicy

What you have would work. You have not mentioned what you meant by above does not work and what your script is.

I tried the C# code with the Powershell script:

param([string]$a)

write-host "test"
write-host $a

and it gave the output:

test
some_parameter

as expected. There is no need to specify -File and -paramter1 like the other answer mentions, but will depend on what your script does.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM