动态生成命令行命令,然后使用powershell调用 [英] Dynamically generate command-line command, then invoke using powershell

查看:33
本文介绍了动态生成命令行命令,然后使用powershell调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 powershell,您可以使用&"运行另一个应用程序并传入参数的字符.

Using powershell, you can use the '&' character to run another application and pass in parameters.

一个简单的例子.

$notepad = 'notepad'
$fileName = 'HelloWorld.txt'

# This will open HelloWorld.txt
& $notepad $fileName   

这很好.但是如果我想使用业务逻辑来动态生成命令字符串呢?使用相同的简单示例:

This is good. But what if I want to use business logic to dynamically generate a command string? Using the same simple example:

$commandString = @('notepad', 'HelloWorld.txt') -join ' ';
& $commandString

我收到错误:

术语记事本HelloWorld.txt"是不被识别为一个名字cmdlet、函数、脚本文件或可运行的程序.检查拼写名称,或者如果路径是包括,验证路径是更正并重试.

The term 'notepad HelloWorld.txt' 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.

在我的真实示例中,我尝试动态添加或删除最终命令行字符串的选项.有什么办法可以解决这个问题吗?

In my real example I'm trying to dynamically add or remove options to the final command line string. Is there a way I can go about this?

推荐答案

两种方法:

将 exe 与参数分开. 为参数执行所有动态操作,但像往常一样调用 exe,然后使用保存参数的变量:

Separate the exe from the arguments. Do all your dynamic stuff for the arguments, but call the exe as normal with the variable holding the arguments afterward:

$argument= '"D:\spaced path\HelloWorld.txt"'
$exe = 'notepad'
&$exe $argument

#or
notepad $argument

如果你有多个参数,如果它与调用的 exe 部分分开,你应该把它做成一个数组:

If you have more than one argument, you should make it an array if it will be separate from the exe part of the call:

$arguments = '"D:\spaced path\HelloWorld.txt"','--switch1','--switch2'
$exe = 'notepad'
&$exe $arguments

使用 Invoke-Expression. 如果所有内容都必须在字符串中,您可以像调用普通表达式一样调用该字符串.Invoke-Expression 也有 iex 的别名.

Use Invoke-Expression. If everything must be in a string, you can invoke the string as if it were a normal expression. Invoke-Expression also has the alias of iex.

$exp = 'notepad "D:\spaced path\HelloWorld.txt"'
Invoke-Expression $exp

在任何一种情况下,参数和 exe 的内容都应该被适当地引用和格式化,就像直接写在命令行上一样.

In either case, the contents of the arguments and of the exe should be quoted and formatted appropriately as if it were being written straight on the commandline.

这篇关于动态生成命令行命令,然后使用powershell调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆