Reputation: 1813
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?
Upvotes: 1
Views: 2339
Reputation: 1798
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
Upvotes: 0
Reputation: 301037
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.
Upvotes: 0
Reputation: 1032
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
}
};
Upvotes: 2