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

前端之家收集整理的这篇文章主要介绍了vb.net – 使用管理员权限运行cmd.exe前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
这是我的代码尝试使用admin priviligies运行cmd.exe.但是,我得到请求操作需要提升.如果我通过我的Windows运行带有“以管理员身份运行”的cmd.exe,它可以通过vb运行,但事实并非如此.这是我的代码.
  1. Try
  2. Dim process As New Process()
  3. process.StartInfo.FileName = "cmd.exe "
  4. process.StartInfo.Verb = "runas"
  5. process.StartInfo.UseShellExecute = False
  6. process.StartInfo.RedirectStandardInput = True
  7. process.StartInfo.RedirectStandardOutput = True
  8. process.StartInfo.RedirectStandardError = True
  9. process.StartInfo.CreateNoWindow = True
  10.  
  11. process.Start()
  12. process.StandardInput.WriteLine("route add 8.31.99.141 mask 255.255.255.255 " & cmdorder)
  13. process.StandardInput.WriteLine("exit")
  14. Dim input As String = process.StandardOutput.ReadToEnd
  15. process.Close()
  16. Dim regex As Regex = New Regex("(ok)+",RegexOptions.IgnoreCase) ' wa requested
  17. ' txtLog.AppendText(input)
  18. Return regex.IsMatch(input)

谢谢.

你无法实现自己想要的目标.

您可以使用Process.Start()来启动提升的进程,但仅当您使用UseShellExecute = true时:

  1. Dim process As New Process()
  2. process.StartInfo.FileName = "cmd.exe "
  3. process.StartInfo.Verb = "runas"
  4. process.StartInfo.UseShellExecute = True
  5. process.Start()

原因是,如果要启动提升的进程,则必须使用ShellExecute.只有ShellExecute知道如何提升.

如果指定UseShellExecute = False,则使用CreateProcess而不是ShellExecute. CreateProcess不知道如何提升.为什么? 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相关文章