正如@mtijn说,你已经得到了很多事情,你以后也覆盖。你还需要确保你正确地逃避了事情。
比方说,你想运行高架下面的命令:
dir c:\
首先,如果你只是跑通过Process.Start()
此命令窗口将弹出打开和关闭的时候了,因为没有什么保持窗口打开。它处理命令并退出。为了保持窗口打开,我们可以包装在单独的命令窗口中的命令,并使用/K
开关以保持其运行:
cmd /K "dir c:\"
要运行该命令提升我们可以使用runas.exe
就像你,不同的是,我们需要转义事情多一点。根据帮助文档(runas /?
),我们传递给runas
的命令中的任何引号需要使用反斜线进行转义。不幸的是,用上面的命令做了这个,给了我们一个双反斜杠,让cmd解析器混淆了,因此也需要转义。所以上面的命令,都会变成:
cmd /K \"dir c:\\\"
最后,使用你提供的,我们可以换一切成一个runas
命令,并在另外一组引号括我们上面命令的语法:
runas /env /user:Administrator "cmd /K \"dir c:\\\""
从命令提示符运行上述命令以确保其按预期工作。
鉴于这一切最终的代码变得更容易组装:
//Assuming that we want to run the following command:
//dir c:\
//The command that we want to run
string subCommand = @"dir";
//The arguments to the command that we want to run
string subCommandArgs = @"c:\";
//I am wrapping everything in a CMD /K command so that I can see the output and so that it stays up after executing
//Note: arguments in the sub command need to have their backslashes escaped which is taken care of below
string subCommandFinal = @"cmd /K \""" + subCommand.Replace(@"\", @"\\") + " " + subCommandArgs.Replace(@"\", @"\\") + @"\""";
//Run the runas command directly
ProcessStartInfo procStartInfo = new ProcessStartInfo("runas.exe");
procStartInfo.UseShellExecute = true;
procStartInfo.CreateNoWindow = true;
//Create our arguments
string finalArgs = @"/env /user:Administrator """ + subCommandFinal + @"""";
procStartInfo.Arguments = finalArgs;
//command contains the command to be executed in cmd
using (System.Diagnostics.Process proc = new System.Diagnostics.Process())
{
proc.StartInfo = procStartInfo;
proc.Start();
}
**是否有可能不使用process.standardinput执行命令?我尝试执行我在参数中传递的命令,但命令没有执行。**您目前没有使用它,所以这个问题没有太大意义。请做你的用户的青睐,并让命令提示符可见,以便他们知道发生了什么。 –
你不想'动词'。这并不意味着你的想法。我认为。 –
@Ramhound procStartInfo.Arguments =“/ env/user:”+“Administrator”+“cmd”+ ** command **; – purvang