2

I have a Ps script which is called from a C# application.

The Powershell script is being called with the format.

            var scriptFile = "./run_script.ps1 " +
                             $"-sql_server {'"' + serverName + '"'} " +
                             $"-database {'"' + dbName + '"'} ";

        MessageBox.Show(scriptFile);

            var startInfo = new ProcessStartInfo
            {
                FileName = @"powershell.exe",
                Arguments = scriptFile,
                RedirectStandardOutput = true,
                RedirectStandardError = true,
                UseShellExecute = false,
                CreateNoWindow = true
            };

            var process = new Process { StartInfo = startInfo };
            process.Start();

The value of servername is being read from a configuration file. The message box comes up with the string below

./run_script.ps1 -sql_server "**Server1,5002**" -database "Test"

However from the script file

param ($sql_server,$database)
write-output "The deployment server is $sql_server"

The output from the C# application can be found below

The deployment server is Server1 5002

It's taking off, for the port number and replacing it with an empty space, thus causing the SQL connection to fail. What is surprising is that when the parameter is printed from the mo

I am lost as to what could be causing this, I have debugged the C# application and I can see that it's sending the string to the Ps file with a,

Useme Alehosaini
  • 2,998
  • 6
  • 18
  • 26
user5544
  • 131
  • 2
  • 9

1 Answers1

3

In your case, the simplest solution is to use the -File CLI parameter explicitly:

Arguments = "-File " + scriptFile

-File ensures that, syntactic "..."-quoting aside, the arguments passed to the script file are interpreted as literals.

Without -File, powershell.exe defaults to -Command / -c, which causes the arguments to be interpreted as a PowerShell command line, which means that, after stripping syntactic "..." quoting around individual arguments, the arguments are space-concatenated and the resulting command line is then interpreted the same way it would be from inside PowerShell, causing the then-unquoted **Server1,5002** to be interpreted as an array.

Note that PowerShell [Core] v6+ (pwsh) now defaults to -File.


Since, as you note in a comment, you do need -Command / -c, due to the need to pass an actual array as one of the arguments (which -File doesn't support), the solution is to either use '...' quoting in your arguments string or embed \"...\"-quoting inside your "..." strings:

var scriptFile = 
  $"./run_script.ps1 -sql_server '{serverName}' -database '{dbName}'";
mklement0
  • 382,024
  • 64
  • 607
  • 775