title: How do I pass variables to powershell through node js
body: <p>I'm trying to runs specific parameterized powershell scripts. Below is a working example</p>
  
  <pre><code>var spawn = require("child_process").spawn,child;
  
  child = spawn("powershell.exe",["c:\\test\\mypstest.ps1 -arg1 1"]);
       child.stdout.on("data",function(data){
       console.log("Powershell Data: " + data);
  });
       child.stderr.on("data",function(data){
       console.log("Powershell Errors: " + data);
  });
  child.on("exit",function(){
       console.log("Powershell Script finished");
  });
  
  child.stdin.end(); //end input
  </code></pre>
  
  <p>Here is an example ps script</p>
  
  <pre><code>param(
      [int]$arg1 = 0
      )
  
  function test(){
      If ($arg1 -eq 0){
      write-host 'too bad'
      }
  
      If ($arg1 -eq 1){
          calc
      }
  
      If ($arg1 -eq 2){ 
          notepad
      }
  }
  test
  </code></pre>
  
  <p>But I need to be able to pass the variables as the arguments for the ps script. I thought this would work.</p>
  
  <pre><code>var str2 = "\"c:\\test\\mypstest.ps1 -arg1";
  var str3 = " 1\"";
  
  var mystr1 = str2.concat(str3);
  
  child = spawn("powershell.exe",[mystr1]);
  </code></pre>
  
  <p>I also tried</p>
  
  <pre><code>function myfunc1(param1, param2){
      var mystr1 = str2.concat(str3);
      //console.log(mystr1);
      return mystr1;
      };
  
  child = spawn("powershell.exe",[myfunc1(str2, str3)]);
  </code></pre>
  
  <p>But i appear to be passed back the variable itself, below is the output i get from the console</p>
  
  <p><em>Powershell Data: c:\test\mypstest.ps1 -arg1 1</em></p>
  
  <p><em>Powershell Script finished</em></p>
  
  <p>And tried this</p>
  
  <pre><code>var str1 = "\"powershell.exe\"\,";
  var str2 = "\[\"c:\\test\\mypstest.ps1 -arg1";
  var str3 = " 1\"\]";
  
  function myfunc1(param1, param2, param3){
      var mystr1 = str1.concat(str2, str3);
      console.log(mystr1);
      return mystr1;
      };
  
  child = spawn(myfunc1(str1, str2, str3));
  </code></pre>
  
  <p>for the above i get an exception</p>
  
  <p><em>events.js:72</em>
  <em>throw er; // Unhandled 'error' event</em>
  <em>Error: spawn ENOENT</em>
  <em>at errnoException (child_process.js:998:11)</em>
  <em>at Process.ChildProcess._handle.onexit (child_process.js:789:34)</em></p>
  
  <p>i'm not fluent in js so any help would be appreciated</p>