powershell传递参数不能正常工作

时间:2017-06-16 20:20:19

标签: powershell batch-file

我遇到了PowerShell脚本的问题。脚本设置参数并尝试执行传入参数的.bat文件。

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

Set-Location $appLoc;    

我已尝试使用

运行批处理脚本传递参数
& $app $arg

& $app -ArgumentList $arg

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

& $app $arg1 $arg2 $arg3

上述所有四个陈述都失败了。它看起来只是执行批处理脚本而不是传入参数。

2 个答案:

答案 0 :(得分:1)

以下是工作代码的演示:

批处理文件“c:\ temp \ psbat.bat”

@echo off
echo one %1
echo two %2

PowerShell文件“c:\ temp \ psbat.ps1”

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

输出

one 1
two 2

Powershell(带变量)

修改上面的powershell以使用变量,我们发现它仍然有效:

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

为什么你的不工作

如果运行上面没有引号的示例,则会执行批处理文件,并将输出返回到$app。因此$app获取值:

one two

当PS尝试稍后执行$app时,它会尝试运行这些PS命令;由于onetwo不是命令,因此失败并出现如下错误:

& : 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.

答案 1 :(得分:1)

有多种选择。请阅读this question。一般来说,这是运行exes的答案。

您可以将参数放在数组中并将它们传递给bat:

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

& $app $args