0

I'm have a small launcher windows app in c# that runs powershell scripts. They are being called as follow:

var ps1File = @"DBScripter.ps1";
var ticketname = this.txtTicketName.Text;
var startInfo = new ProcessStartInfo()
{
    FileName = "powershell.exe",
    Arguments = $"-NoProfile -ExecutionPolicy unrestricted -file \"{ps1File}\" -TicketName \"{ticketname}\"",
    UseShellExecute = false
};
Process.Start(startInfo);

This is working fine, but if I add a non-mandatory boolean param to the call like this:

var ps1File = @"DBScripter.ps1";
var ticketname = this.txtTicketName.Text;
bool release = true;
var startInfo = new ProcessStartInfo()
{
    FileName = "powershell.exe",
    Arguments = $"-NoProfile -ExecutionPolicy unrestricted -file \"{ps1File}\" -TicketName \"{ticketname}\" -IsProdRelease \"{release}\"",
    UseShellExecute = false
};
Process.Start(startInfo);

This does not work, whether I send a boolean, a string with $True or $true or an Integer with 1.

In the PS script, parameters are declared as follow:

param (
    [Parameter(Mandatory = $false)]
    [string]$TicketName,
    [Parameter(Mandatory = $false)]
    [string]$TicketPath,
    [Parameter(Mandatory = $false)]
    [boolean]$IsProdRelease
)

How should I pass this value from c# to the PS file execution?

davidc2p
  • 320
  • 3
  • 9
  • You need $true instead of true. Arguments are a string that gets translated to by the loader into an object. – jdweng Jun 14 '23 at 09:21
  • Does this answer your question? [Execute PowerShell Script from C# with Commandline Arguments](https://stackoverflow.com/questions/527513/execute-powershell-script-from-c-sharp-with-commandline-arguments) – Charlieface Jun 14 '23 at 10:16
  • You don't need to start `powershell.exe` you can execute it directly from C# – Charlieface Jun 14 '23 at 10:17

2 Answers2

0

As jdweng mentions, the PowerShell equivalent of true is the special variable $true:

Arguments = $"... -IsProdRelease:${release}"

A better option is to type the script parameter as a [switch] instead of a [boolean] - this way you don't need an argument value, presence of the named parameter switch itself is enough:

var startInfo = new ProcessStartInfo()
{
    FileName = "powershell.exe",
    Arguments = $"-NoProfile -ExecutionPolicy unrestricted -file \"{ps1File}\" -TicketName \"{ticketname}\"",
    UseShellExecute = false
};

if (release)
{
    startInfo.Arguments += " -IsProdRelease";
}

Binding a boolean literal (like in the example above) will also still work with [switch] parameters.

Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206
0

I couldn't make it work! I've changed the script to use the param as a string and pass 'true' as a string.

It works now. Thank you all.

davidc2p
  • 320
  • 3
  • 9