有条件(例如/h或其他条件)以管理员身份打开程序 [英] Open a program as administrator with conditions (e.g. /h or something)
问题描述
我想使用 Start-Process
批量但有条件地使用PowerShell运行程序.
I want to run a program with PowerShell using Start-Process
in a batch but with conditions.
我对其进行了测试,并使用 Start-Process
命令运行了 cmd/c
.
I tested it and I ran cmd /c
using the Start-Process
command.
命令:
powershell -Command "Start-Process `cmd /c` -Verb runas"
那没有用.
所以我在PowerShell上对其进行了测试.尝试了相同的命令,并返回此错误:
So I tested it on PowerShell. Tried the same command and it returned this error:
Start-Process : A positional parameter cannot be found that accepts argument
'runas'.
At line:1 char:14
+ Start-Process <<<< 'cmd /c' -Verb runas
+ CategoryInfo : InvalidArgument: (:) [Start-Process], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.StartProcessCommand
如何使用 powershell
命令在主PowerShell上批量处理此问题?
How can I make this work on batch using powershell
command and on the main PowerShell?
推荐答案
反引号是PowerShell的转义字符.在声明中
The backtick is PowerShell's escape character. In a statement
Start-Process `cmd /c` -Verb runas
反引号转义 cmd
的 c
和/c
后的空格.前者没有问题,因为它只是使 c
成为文字 c
(无论如何).但是,转义/c
和 -Verb
之间的空格有效地将整个序列/c -Verb
变成单个字符串.基本上,与您运行以下语句相同:
the backticks escape the c
of cmd
and the space following the /c
. The former isn't problematic, because it just makes the c
a literal c
(which it is anyway). However, escaping the space between /c
and -Verb
effectively turns the whole sequence /c -Verb
into a single string. Basically it's the same as if you'd run this statement:
Start-Process cmd "/c -Verb" runas
自 Start-Process
仅接受2个位置参数( -FilePath
和 -ArgumentList
),其他所有参数都必须通过命名参数传递.因此,关于没有位置参数接受参数 runas
的错误.
Since Start-Process
accepts only 2 positional parameters (-FilePath
and -ArgumentList
) everything else must be passed via named parameters. Hence the error about no positional parameter accepting the argument runas
.
像这样运行命令:
Start-Process cmd /c, dir, "$env:windir\temp" -Verb runas
或
Start-Process -FilePath 'cmd.exe' -ArgumentList '/c', 'dir', "$env:windir\temp" -Verb runas
或类似(来自CMD):
or like this (from CMD):
powershell.exe -Command "Start-Process cmd /c, dir, \"$env:windir\temp\" -Verb runas"
,它将按您期望的那样工作.
and it will work as you'd expect.
修改
由于显然一开始还不够清楚: -ArgumentList
参数的参数是逗号分隔的列表(数组).
Edit
Since apparently it wasn't clear enough initially: the argument for the -ArgumentList
parameter is a comma-separated list (an array).
Start-Process cmd /c, dir, "$env:windir\temp" -Verb runas
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^
# this right here
这篇关于有条件(例如/h或其他条件)以管理员身份打开程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!