0

I am having an issue with a powershell script. The script set parameter and tries to execute a .bat file passing in the parameters.

$app='test.bat';
$appLoc='C:\scripts';
$arg1='userid';
$arg2='password';    
$arg3='filelocation';
$arg= $arg1 + $arg2 + $arg3;

Set-Location $appLoc;    

I have tried everything to run the batch script passing in the parameters using

& $app $arg

& $app -ArgumentList $arg

Start-Process $app -ArgumentList $arg -wait -passthru

& $app $arg1 $arg2 $arg3

All four statements above is failing. It looks like it is only executing the batch script and not passing in the parameters.

Duc
  • 21
  • 4
  • 1
    Is it really like that `$app=test.bat;` without any quotes? – user4003407 Jun 16 '17 at 20:22
  • 1
    `$app=test.bat` is running the batch file right away, unless it's in the current folder then it's throwing an error. `$arg1=userid;` is not valid powershell, it's an error (or it's running a command called 'userid'?). `-ArgumentList` takes a list (array) and you're passing it a string. Please edit to include some actual code that demonstrates what you're doing and what's going wrong.. – TessellatingHeckler Jun 16 '17 at 20:31

2 Answers2

1

Here's a demo of working code:

Batch File "c:\temp\psbat.bat"

@echo off
echo one %1
echo two %2

PowerShell File "c:\temp\psbat.ps1"

Push-Location 'c:\temp\'
& '.\psbat.bat' 1 2
Pop-Location

Output

one 1
two 2

Powershell (with variables)

Amending the powershell above to use variables, we find it still works:

Push-Location 'c:\temp\'
$app = '.\psbat.bat'
$arg1 = 'argument 1'
$arg2 = 2
&$app $arg1 $arg2
Pop-Location

Why yours isn't working

If you run the above example without the quotes, the batch file gets executed, and the output is returned to $app. So $app gets the value:

one two

When PS tries to later execute $app, it tries to run those PS commands; and since one and two aren't commands, it fails with an error such as:

& : The term 'one  two  ' is not recognized as the name of a cmdlet, 
function, script file, or operable program. Check the spelling of the 
name, or if a path was included, verify that the path is correct and 
try again.
JohnLBevan
  • 22,735
  • 13
  • 96
  • 178
1

There are multiple options. Please read this question. It is an answer to run exes in general.

You can put your parameters in an array and pass them to the bat:

$app = 'test.bat'
$args = @()    
$args += 'userid'
$args += 'password'
$args += 'filelocation'

& $app $args
MarliesV
  • 65
  • 3