1

I am trying to setup a simple .aspx web page that will accept a user's input of a string (later, more than one string) and use that string as the parameter value for a Powershell script.

The PS script looks like this right now:

[CmdletBinding()]
param (
    [string] $ServiceName
)

$ServiceName | out-file c:\it\test.txt 
$ServiceName | Out-String

The C# code looks like this:

var shell = PowerShell.Create();

// Add the script to the PowerShell object
shell.Commands.AddScript("C:\\it\\test.ps1 -ServiceName BITS");

// Execute the script
var results = shell.Invoke();

When I run that, I get "BITS" written to the test.txt file. What I need to do now, is setup the application to call the script, passing in the "ServiceName" parameter. I found this: Call PowerShell script file with parameters in C# and tried the following code:

PowerShell ps = PowerShell.Create();
ps.AddScript(@"c:\it\test.ps1").AddParameter("ServiceName", "BITS");
var results = ps.Invoke();

In this case, the script was called and the test.txt file was created, but the value (BITS) was not written to the file. What am I missing here? Why isn't the parameter being passed to the script?

Thanks.

2 Answers 2

0

I ended up using

var ps = @"C:\it\test.ps1";
processInfo = new ProcessStartInfo("powershell.exe", "-File " + ps + " -ServiceName BITS);

I don't like this as much, but it works. shrug

Sign up to request clarification or add additional context in comments.

Comments

0

Here are three possible solutions for future readers including me:

using (PowerShell ps = PowerShell.Create())
{
   //Solution #1
   //ps.AddCommand(@"C:\it\test.ps1", true).AddParameter("ServiceName", "BITS");
   //Solution #2
   //ps.AddScript(@"C:\it\test.ps1 -ServiceName 'BITS'", true);
   //Solution #3
   ps.AddScript(File.ReadAllText(@"C:\it\test.ps1"), true).AddParameter("ServiceName", "BITS");

   Collection<PSObject> results = ps.Invoke();
} 

I haven't seen solution #3 documented anywhere else, though I got the idea for it from https://blogs.msdn.microsoft.com/kebab/2014/04/28/executing-powershell-scripts-from-c/

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.