运行 Powershell 中从变量中获取的 cmd + args 的正确方式是什么?

huangapple go评论67阅读模式
英文:

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"

huangapple
  • 本文由 发表于 2023年6月27日 21:04:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/76565171.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定