正如@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