Search code examples
batch-filecmdcommand

How Can I execute a batch file i back ground using & ampersand in command line, but passing parameters?


I have the following batch file:

    cd C:\myfolder\MyScripts
    "C:\Program Files\nodejs\node.exe" runTest.js & %1

The %1 is a parameter that I send from a c# application.

The & is a command that allows to execute the process in background (this is mandatory for my purposes)

My problem is that the command line stops in the ampersand, and doesn't send the parameter to my file. If I put "C:\Program Files\nodejs\node.exe" runTest.js %1 & with ampersand at the end, the process doesn't run in background and stops.

Can someone help me?

I need to let the process running in background AND send the parameter.

Note: If I hardcode a value in the batch file It works fine, for example:

"C:\Program Files\nodejs\node.exe" runTest.js & 500

but when I use the syntax to pass a parameter value, it fails. thank you so much!


Solution

  • For all those with the same problem as me, this is how i solved it:

    I change cmd to powershell.

    So the C# code finished like this:

     process.StartInfo.FileName = @"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe";
     process.StartInfo.Arguments = $"-File \"{ScriptNameOne}\" \"{param1}\"  \"{param2}\" \"{param3}\"";
     process.StartInfo.UseShellExecute = true;
     process.Start();
    

    And I did the script in powershell like this:

    param(
        [string] $param1, 
        [string] $param2,
        [string] $param3
    )
    Set-Location "C:\My folder\My other folder"
    & "C:\Program Files\nodejs\node.exe" "index.js" $param1 $param2 $param3 
    

    And works perfectly as I needed.