将参数传递给外部命令-停止解析

时间:2018-06-25 13:54:46

标签: powershell

我是PowerShell的新手,正在尝试在调用外部cmd时停止解析。示例代码:

$Exe = "C:\Program Files\Test\keygen.exe"
# Execute command with arguments
$Exe --% "-Z"

我认为--%可以正确停止分析器,但这会返回错误“'-操作符仅适用于数字。操作数为'System.String'。

这是怎么了?

1 个答案:

答案 0 :(得分:0)

您将命令定义为字符串。 PowerShell的默认行为是回显字符串并执行裸词:

PS C:\> ping.exe 127.0.0.1

Pinging 127.0.0.1 with 32 bytes of data:
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128

Ping statistics for 127.0.0.1:
    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 0ms, Maximum = 0ms, Average = 0ms
PS C:\> $exe = 'ping.exe'
PS C:\> $exe
ping.exe
PS C:\> $exe 127.0.0.1
At line:1 char:6
+ $exe 127.0.0.1
+      ~~~~~~~~~
Unexpected token '127.0.0.1' in expression or statement.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : UnexpectedToken

您需要使用call operator&)使PowerShell执行字符串命令:

PS C:\> & $exe 127.0.0.1

Pinging 127.0.0.1 with 32 bytes of data:
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128

Ping statistics for 127.0.0.1:
    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 0ms, Maximum = 0ms, Average = 0ms