如何将带点的批处理参数传递给powershell脚本?

时间:2014-10-28 17:42:32

标签: windows powershell batch-file

我有一个批处理脚本,它将由不受我控制的外部进程运行。外部进程可以为批处理脚本提供可变数量的参数。然后我想将这些变量传递给powershell脚本。问题是,这些变量中的一些看起来像是:

-Dfoo.bar =巴兹

Powershell出于某种原因将其分为两个方面。在命令行中,我可以在arg周围添加引号并将其称为一天。但是我如何通过这种方式获得批量传递呢?这是我的剧本:

@echo off
SET CMD=C:\Scripts\foo.ps1

PowerShell.Exe -Command "%CMD%" %*

我注意到这个问题与this one非常相似。在这里,他逃脱了这个角色。我尝试为点和/或短划线字符做类似的事情,但没有运气。有人有什么想法吗?

3 个答案:

答案 0 :(得分:4)

如果你从CMD调用你的脚本,它可以正常工作:

C:\>.\foo.bat -Dfoo.bar=baz
args are -Dfoo.bar=baz

要解决从PowerShell运行批处理脚本时出现的问题,请使用stop parsing operator --%例如:

C:\ PS> .\foo.bat --% -Dfoo.bar=baz
args are -Dfoo.bar=baz

答案 1 :(得分:1)

要以文字形式传递内容,您可以将它们用单引号括起来。我的建议是为你的参数做这个,然后在PowerShell中将它们分解一次,然后将它们发送给你的命令。

@echo off
SET CMD=C:\Scripts\foo.ps1

PowerShell.Exe -Command "%CMD%" '%*'

然后在Powershell:

Param($PassedArgs)
$SplitArgs = $PassedArgs.trim("'").split(" ")
SomeCommand @SplitArgs

答案 2 :(得分:1)

这样的事可能有用:

@echo off

set "CMD=C:\Scripts\foo.ps1"
set "ARGS=%*"
set "ARGS=%ARGS: =' '%"

PowerShell.Exe -Command "%CMD%" '%ARGS%'

演示:

C:\>type test.cmd
@echo off

set "CMD=C:\test.ps1"
set "args=%*"
set "args=%args: =' '%"
powershell -Command "%CMD%" '%args%'

C:\>type test.ps1
$args | % { $_ }

C:\>test.cmd -Dfoo.bar=baz -something
-Dfoo.bar=baz
-something

参数周围的单引号阻止PowerShell使用该参数执行时髦的事情。通过用' '替换参数列表中的空格,可以在一个参数之后和下一个参数之前放置单引号。 "外部"变量周围的单引号在第一个参数之前和之后添加缺少的引号。

C:\>type test2.cmd
@echo off
set "args=%*"
echo %args%
set "args=%args: =' '%"
echo %args%
echo '%args%'

C:\>test2.cmd -Dfoo.bar=baz -something
-Dfoo.bar=baz -something
-Dfoo.bar=baz' '-something
'-Dfoo.bar=baz' '-something'
相关问题