gpt4 book ai didi

vb.net - 使用管理员权限运行 cmd.exe

转载 作者:行者123 更新时间:2023-12-02 22:54:06 25 4
gpt4 key购买 nike

这是我尝试以管理员权限运行 cmd.exe 的代码。但是,我收到请求操作需要提升。如果我通过 Windows 以“以管理员身份运行”运行 cmd.exe,它可以工作,但是,通过 vb,则不能。这是我的代码。

Try
Dim process As New Process()
process.StartInfo.FileName = "cmd.exe "
process.StartInfo.Verb = "runas"
process.StartInfo.UseShellExecute = False
process.StartInfo.RedirectStandardInput = True
process.StartInfo.RedirectStandardOutput = True
process.StartInfo.RedirectStandardError = True
process.StartInfo.CreateNoWindow = True

process.Start()
process.StandardInput.WriteLine("route add 8.31.99.141 mask 255.255.255.255 " & cmdorder)
process.StandardInput.WriteLine("exit")
Dim input As String = process.StandardOutput.ReadToEnd
process.Close()
Dim regex As Regex = New Regex("(ok)+", RegexOptions.IgnoreCase) ' wa requested
' txtLog.AppendText(input)
Return regex.IsMatch(input)

谢谢。

最佳答案

你无法实现你想要的。

可以使用Process.Start()启动提升的进程,但如果您UseShellExecute = true:

Dim process As New Process()
process.StartInfo.FileName = "cmd.exe "
process.StartInfo.Verb = "runas"
process.StartInfo.UseShellExecute = True
process.Start()

原因是因为如果您想启动提升的进程,您必须使用ShellExecute。只有 ShellExecute 知道如何提升。

如果您指定UseShellExecute = False,则使用CreateProcess,而不是ShellExecuteCreateProcess 不知道如何提升。为什么? From the AppCompat guy:

Well, CreateProcess is really low in the layers. What can you do without the ability to create a process? Not a whole lot. Elevation, however, is a different story. It requires a trip to the app elevation service. This then calls into consent.exe, which has to know how to read group policy and, if necessary, switch to the secure desktop and pop open a window and ask the user for permission / credentials, etc. We don’t even need to take all of these features, let’s just take the dialog box.

Now, for creating a process that requires elevation, normally you just switch up APIs. The shell sits in a much higher layer, and consequently is able to take a dependency on elevation. So, you’d just swap out your call to CreateProcess with a call to ShellExecute.

这解释了如何提升cmd,但是一旦你这样做了:你就不能重定向输出,或隐藏窗口; as only CreateProcess can do that:

Redirecting I/O and hiding the window can only work if the process is started by CreateProcess().

这家伙问 same question over here 的说法有点长了。 ;但不要因为有人结束你的问题而感到侮辱。

Note: Any code is released into the public domain. No attribution required.

关于vb.net - 使用管理员权限运行 cmd.exe,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17843457/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com