【问题标题】:powershell to pass parameter not working correctlypowershell传递参数无法正常工作
【发布时间】:2017-11-19 17:03:20
【问题描述】:

我遇到了有关 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

以上四个语句都失败了。貌似只是执行批处理脚本,没有传入参数。

【问题讨论】:

  • 真的像$app=test.bat;那样不加引号吗?
  • $app=test.bat 正在立即运行批处理文件,除非它在当前文件夹中,否则它会引发错误。 $arg1=userid; 不是有效的 powershell,它是一个错误(或者它正在运行一个名为 'userid' 的命令?)。 -ArgumentList 接受一个列表(数组),然后您将其传递给一个字符串。请编辑以包含一些实际代码,以演示您在做什么以及出了什么问题..

标签: powershell batch-file


【解决方案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.

【讨论】:

    【解决方案2】:

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

    你可以把你的参数放在一个数组中,然后把它们传给bat:

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

    【讨论】:

      猜你喜欢
      • 2020-03-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-24
      • 2021-02-25
      • 2014-02-22
      • 1970-01-01
      • 2022-11-13
      • 1970-01-01
      相关资源
      最近更新 更多