如何从字符串执行任意本机命令? [英] How do you execute an arbitrary native command from a string?
问题描述
我可以通过以下场景表达我的需求:编写一个接受字符串作为本机命令运行的函数.
I can express my need with the following scenario: Write a function that accepts a string to be run as a native command.
一个想法并不太牵强:如果您正在与公司其他地方的其他命令行实用程序交互,这些实用程序为您提供逐字运行的命令.因为您不控制命令,所以您需要接受任何有效的命令作为输入.这些是我一直无法轻松克服的主要问题:
It's not too far fetched of an idea: if you're interfacing with other command-line utilities from elsewhere in the company that supply you with a command to run verbatim. Because you don't control the command, you need to accept any valid command as input. These are the main hiccups I've been unable to easily overcome:
该命令可能会执行存在于路径中且其中包含空格的程序:
The command might execute a program living in a path with a space in it:
$command = '"C:\Program Files\TheProg\Runit.exe" Hello';
该命令可能包含带空格的参数:
The command may have parameters with spaces in them:
$command = 'echo "hello world!"';
该命令可能有单引号和双引号:
The command might have both single and double ticks:
$command = "echo `"it`'s`"";
是否有任何干净的方法来实现这一目标?我只能设计出奢华而丑陋的解决方法,但对于脚本语言,我觉得这应该非常简单.
Is there any clean way of accomplishing this? I've only been able to devise lavish and ugly workarounds, but for a scripting language I feel like this should be dead simple.
推荐答案
Invoke-Expression
,别名为 iex
.以下内容适用于您的示例 #2 和 #3:
Invoke-Expression
, also aliased as iex
. The following will work on your examples #2 and #3:
iex $command
某些字符串不会按原样运行,例如您的示例 #1,因为 exe 是在引号中.这将按原样工作,因为字符串的内容正是您从 Powershell 命令提示符直接运行它的方式:
Some strings won't run as-is, such as your example #1 because the exe is in quotes. This will work as-is, because the contents of the string are exactly how you would run it straight from a Powershell command prompt:
$command = 'C:\somepath\someexe.exe somearg'
iex $command
但是,如果 exe 是在引号中,则需要 &
的帮助才能使其运行,如本示例中所示,从命令行运行:
However, if the exe is in quotes, you need the help of &
to get it running, as in this example, as run from the commandline:
>> &"C:\Program Files\Some Product\SomeExe.exe" "C:\some other path\file.ext"
然后在脚本中:
$command = '"C:\Program Files\Some Product\SomeExe.exe" "C:\some other path\file.ext"'
iex "& $command"
很可能,您可以通过检测命令字符串的第一个字符是否为 "
来处理几乎所有情况,就像在这个简单的实现中一样:
Likely, you could handle nearly all cases by detecting if the first character of the command string is "
, like in this naive implementation:
function myeval($command) {
if ($command[0] -eq '"') { iex "& $command" }
else { iex $command }
}
但是您可能会发现其他一些必须以不同方式调用的情况.在这种情况下,您可能需要使用 try{}catch{}
(可能针对特定的异常类型/消息)或检查命令字符串.
But you may find some other cases that have to be invoked in a different way. In that case, you will need to either use try{}catch{}
, perhaps for specific exception types/messages, or examine the command string.
如果您总是收到绝对路径而不是相对路径,那么除了上述 2 种情况之外,您不应该有很多特殊情况(如果有).
If you always receive absolute paths instead of relative paths, you shouldn't have many special cases, if any, outside of the 2 above.
这篇关于如何从字符串执行任意本机命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!