如何使用需要从命令提示符/批处理文件中引用的参数来调用PowerShell Start-Process命令? [英] How I do invoke a PowerShell Start-Process command with arguments that require quoting from a Command Prompt / batch file?

查看:145
本文介绍了如何使用需要从命令提示符/批处理文件中引用的参数来调用PowerShell Start-Process命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PowerShell中尝试执行一个命令时出现此错误:

I am getting this error when trying exec one command in PowerShell:

我正在尝试exec此命令:

powershell.exe Start-Process -FilePath "C:\Windows\System32\attrib +h +s "%CD%"" -Verb runAs

有人可以帮我弄清楚为什么会发生这种情况以及如何解决吗?

Can someone please help me figuring out why this is happening and how to solve it?

推荐答案

有人可以帮我弄清楚为什么会这样吗?

Can someone please help me figure out why this is happening?

Start-Process cmdlet的-FilePath参数需要一个可执行文件 的名称或路径,而不是一个 entire命令行.

The -FilePath parameter of the Start-Process cmdlet expects the name or path of an executable file by itself, not an entire command line.

要传递给通过-FilePath指定的可执行文件的自变量必须通过-ArgumentList作为数组单独传递 . (-Args)参数.

The arguments to pass to the executable specified via -FilePath must be passed separately, as an array, via the -ArgumentList (-Args) parameter.

cmd.exe(批处理文件)进行调用时,从概念上讲,更干净的方法是在单个"括起来的参数中传递要由 PowerShell 进行评估的整个命令行:

When calling from cmd.exe (a batch file), it's conceptually cleaner to pass the entire command line to be evaluated by PowerShell in a single, "-enclosed argument:

powershell.exe -Command "Start-Process -Verb RunAs -FilePath attrib.exe -Args +h, +s, '\"%CD%\"'"

请注意需要转义%CD% ,方法是先将其封装在'中,然后再放在\"中: PowerShell本身会将值识别为单个参数,而嵌入式\"引号可确保最终目标程序attrib.exe也将该值也视为单个参数.

Note the need to escape the %CD% value doubly, by enclosing it in ' for the sake of PowerShell first, then in \" inside that: The outer ' ensures that PowerShell itself recognizes the value as a single argument, and the embedded \" quoting ensures that the ultimate target program, attrib.exe, sees the value as a single argument too.

不幸的是,这种双重转义的需求是不幸的,并且不是必须的-在中对此进行了讨论GitHub问题.

This need for double escaping is unfortunate and shouldn't be necessary - it is discussed in this GitHub issue.

这篇关于如何使用需要从命令提示符/批处理文件中引用的参数来调用PowerShell Start-Process命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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