[英]Converting C# Application that runs CMD commands to one that runs Powershell commands with administrative privileges
我有一個Visual Studio應用程序,它使用以下功能運行一系列Cmd命令
public static void AdminEx(string command) //Runs an Administrative Windows Command
{
var proc = new System.Diagnostics.ProcessStartInfo();
proc.UseShellExecute = true;
proc.WorkingDirectory = @"C:\Windows\System32";
proc.FileName = @"C:\Windows\System32\cmd.exe";
proc.Verb = "runas";
proc.Arguments = "/c " + command;
proc.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
var p = System.Diagnostics.Process.Start(proc);
p.WaitForExit();
}
我們最近更新了代碼,並轉換為Powershell。 我將如何更改此功能以適應新代碼。 這仍然是最有效的方法嗎???
只需更改行:
proc.FileName = @"C:\Windows\System32\cmd.exe";
至:
proc.FileName = @"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe";
這將使您的軟件打開powershell.exe而不是cmd.exe,我無法確定這是否是解決此問題的最佳方法,但是我在這里嘗試了一下,並且對我有用。
奧塔維奧·卡爾多納佐(OtávioCaldonazo)的有用答案提供了有效的解決方案,但值得解釋以下幾點:
除非有安全方面的考慮(有人將非標准的惡意cmd.exe
/ powershell.exe
可執行文件放在%PATH%
/ $env:PATH
環境變量中列出的文件夾中,這些文件優先於標准可執行文件),否則使用僅可執行文件名 ,即cmd.exe
/ powershell.exe
這還避免了根不是 C:\\Windows
的非標准Windows安裝的問題。
.FileName
,該.WorkingDirectory
財產與忽略 .Verb
設置為runas
,因為.WorkingDirectory
那么實際上並沒有設置工作目錄 ,而是指定在哪里查找可執行文件 ,如果僅按名稱指定-但是,仍會執行%PATH%
/ $env:PATH
中的查找。 雖然/c
參數傳遞一個命令來調用的外殼會發生使用PowerShell的命令行工作過,PowerShell的一般使用印記-
以前綴參數名稱 ; 從而,
-c
( -Command
)是更好的選擇。
$PROFILE
默認初始化文件(即使與調用-Command
或-File
,盡管這通常是不希望), 最好使用-NoProfile -Command ...
代替。 一般 -如果你不需要 海拔 (運行作為管理員 ) -作為替代-慢-通過創建子進程的powershell.exe
,考慮使用的PowerShell的SDK(API) ,實現了更高的進程執行,同時還可以實現更細粒度的輸出流捕獲 (您似乎對特定場景不感興趣;而System.Diagnostics.ProcessStartInfo
允許您通過.RedirectStandardOutput
和.RedirectStandardError
屬性捕獲stdout和stderr輸出,請注意,PowerShell具有其他輸出流 )。
基於以上內容,我建議您執行以下操作:
var proc = new System.Diagnostics.ProcessStartInfo();
proc.UseShellExecute = true;
proc.Verb = "runas";
proc.FileName = @"powershell.exe";
proc.Arguments = "-NoProfile -Command " + command;
proc.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
var p = System.Diagnostics.Process.Start(proc);
p.WaitForExit();
或者,更簡潔地說:
using System;
using System.Diagnostics;
var proc = new ProcessStartInfo()
{
UseShellExecute = true,
Verb = "runas",
WindowStyle = ProcessWindowStyle.Hidden,
FileName = "powershell.exe",
Arguments = "-NoProfile -Command " + command
};
Process.Start(proc).WaitForExit();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.