将字符串从 vb.net 传递到 cmd
Posted
技术标签:
【中文标题】将字符串从 vb.net 传递到 cmd【英文标题】:Passing string from vb.net to cmd 【发布时间】:2019-07-18 13:48:11 【问题描述】:我正在尝试将字符串从 vb.net 传递到命令提示符窗口。最后,我想使用 runas 并使用之前在登录应用程序时提供的密码作为密码。基本上我想运行 runas 命令,然后在窗口中输入密码(或以某种方式将其提供给 cmd)
Public Sub runCmd(ByVal pass As String, ByVal command As String, ByVal arguments As String, ByVal permanent As Boolean)
Dim p As Process = New Process()
Dim pi As ProcessStartInfo = New ProcessStartInfo()
pi.Arguments = " " + If(permanent = True, "/K", "/C") + " " + command + " " + arguments
pi.FileName = "cmd.exe"
pi.Verb = "runas"
p.StartInfo = pi
p.Start()
End Sub
这是我得到目录错误的更新代码
Public Sub runCmd(ByVal pass As String, ByVal user As String, ByVal domainName As String, ByVal command As String, ByVal arguments As String, ByVal permanent As Boolean)
Dim p As Process = New Process()
Dim pi As ProcessStartInfo = New ProcessStartInfo()
pi.Arguments = " " + If(permanent = True, "/K", "/C") + " " + command + " " + arguments
pi.FileName = "cmd.exe"
pi.Verb = "runas"
pi.UserName = user
pi.Domain = domainName
pi.Password = getSecureString(pass)
p.StartInfo = pi
pi.UseShellExecute = False
p.Start()
End Sub
【问题讨论】:
你试过看here吗? 是的,使用 createprocesswithlogonW 会给我一个提升错误,我正在使用 runas 作为解决方法,因为我无法禁用 UAC。 【参考方案1】:不能同时在不同的用户帐户下以提升的权限启动Process
。所以,我根据Can I get UAC prompt for user from batch file?修改了你的runCmd
函数如下。动态创建一个脚本,其中包含以提升的权限运行的命令。然后使用Process
在所需的用户帐户下运行该脚本。
Public Sub runCmd(ByVal password As String, ByVal user As String, ByVal domain As String, ByVal command As String, ByVal permanent As Boolean)
' Create script with desired command to run under elevated prompt.
Dim persist As String = If(permanent, "/K ", "/C ")
File.WriteAllText(
"runCmd.js",
$"ShA=new ActiveXObject(""Shell.Application"")" & vbCrLf &
$"ShA.ShellExecute(""cmd.exe"",""persist command"","""",""runas"",5);")
' Run script as domain\user with password.
Dim p As Process = New Process()
Dim pi As ProcessStartInfo = New ProcessStartInfo()
pi.Arguments = "runCmd.js"
pi.FileName = "wscript.exe"
pi.UserName = user
pi.Domain = domain
pi.Password = GetSecureString(password)
p.StartInfo = pi
pi.UseShellExecute = False
p.Start()
End Sub
其中GetSecureString()
函数定义如下。
Public Function GetSecureString(ByVal str As String) As SecureString
Dim secureString As SecureString = New SecureString
For Each ch As Char In str
secureString.AppendChar(ch)
Next
secureString.MakeReadOnly()
Return secureString
End Function
例如,您可以调用:
runCmd("password", "user", "domain", "dir", True)
您将收到 UAC 提示,将打开一个命令窗口,运行 dir
命令,并且命令窗口将保持打开状态。
您可以通过查看ShellExecute 和wscript 提供的不同选项来进一步定制您的解决方案。
【讨论】:
@Adam - 那是你要找的吗? @Adam - 没有收到您的来信。 抱歉耽搁了,我试过了,但在 process.start 行出现错误,提示“目录名称无效” @ Adam - 您能否将新代码附加到原始问题中?您在收到错误时使用的runCmd()
参数的值是什么?
@Adam - 你在收到错误时使用的 runCmd() 参数的值是多少?以上是关于将字符串从 vb.net 传递到 cmd的主要内容,如果未能解决你的问题,请参考以下文章
将 QueueClientOptions 传递给 VB.NET 中的 Queueclient 构造函数