英文:
What is the right the way to run cmd + args from a variable using powershell?
问题
以下是翻译好的部分:
你可以如何在cmd中使用PowerShell运行包含变量的命令和参数?
以下是有效的示例:
powershell -c "& $test='dir'; &($test)"
但是,当你向命令提供参数时,例如:
dir /a -> powershell -c "& $test='dir /a'; &($test)"
你会遇到以下错误:
&: 未将项 'dir /a' 识别为 cmdlet、函数、脚本文件或可运行的程序的名称。请检查名称的拼写,或者如果包括路径,请验证路径是否正确,然后重试。
以下是尝试但未成功的方法:
powershell -c "& $test='dir /a'; Invoke-Expression '&$test'"
powershell -c "& $test='dir /a'; Invoke-Expression ""&($test)"""
powershell -c "& $test='dir /a'; Invoke-Expression '&($test)'
powershell -c "& $test='dir /a'; Invoke-Expression &($test)"
如何执行$test的内容,而无需使用cmd进行管道传输?
英文:
How can I run a command + arguments inside a variable using powershell from cmd?
This is what works fine:
powershell -c " $test='dir'; &($test) "
But when I supply an argument to the command, for example:
dir /a -> powershell -c " $test='dir /a'; &($test) "
I get this error:
&: The term 'dir /a' 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 line:1 char:19
+ $test='dir /a'; &($test)
+ ~~~~~~~
+ CategoryInfo : ObjectNotFound: (dir /a:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
This is what I tried but did not work:
powershell -c " $test='dir /a'; &($test) "
powershell -c " $test='dir /a'; Invoke-Expression '&$test' "
powershell -c " $test='dir /a'; Invoke-Expression """&($test)""" "
powershell -c " $test='dir /a'; Invoke-Expression '&($test)' "
powershell -c " $test='dir /a'; Invoke-Expression &($test) "
How can I execute the content of $test, without pipeing to cmd?
答案1
得分: 1
以下是翻译好的部分:
错误已经说明了一切 - 'dir /a'
不是一个可见的 PowerShell 命令的名称!
将命令名称和参数分开,它就会工作:
powershell -c "$cmd = 'dir'; $arg = '/a'; &$cmd $arg"
请注意,PowerShell 不是 cmd.exe
- 如果您想在 cmd.exe
中运行一个一次性命令,您需要调用 cmd.exe
,然后是 /c
命令行开关,然后是您想要执行的命令表达式:
powershell -c "$cmd = 'cmd.exe'; $arg = '/c','dir','/a'; &$cmd @arg"
请注意,只返回翻译好的部分。
英文:
The error says it all - 'dir /a'
is not the name of a visible PowerShell command!
Split the command name and arguments into separate parts and it'll work:
powershell -c "$cmd = 'dir'; $arg = '/a'; &$cmd $arg"
Note that PowerShell is not cmd.exe
- if you want to run a one-off command in cmd.exe
, you'll need to invoke cmd.exe
, followed by the /c
command line switch and then the command expression you want it to execute:
powershell -c "$cmd = 'cmd.exe'; $arg = '/c','dir','/a'; &$cmd @arg"
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论