从.Net调用的批处理文件无法运行

时间:2014-09-18 15:43:51

标签: .net vb.net visual-studio-2010 batch-file

我正在尝试从我的Vb.Net应用程序运行批处理文件。 VS 2010瞄准.Net 4。

在Windows XP下运行正常。

在Windows 8下,我按预期获得了UAC提示,并且我看到命令窗口短暂出现,但它立即消失,并且批处理文件中的所有命令似乎都没有执行。

我尝试用一​​个pause命令替换批处理文件,但窗口仍然只是消失而不等待输入。 这是我的代码:

    processStartInfo = New System.Diagnostics.ProcessStartInfo()
    processStartInfo.FileName = Script  ' batch file name

    If My.Computer.Info.OSVersion >= "6" Then  ' Windows Vista or higher
        ' required to invoke UAC
        processStartInfo.Verb = "runas"
    End If

    processStartInfo.Arguments = Join(Parameters, " ")
    processStartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal
    processStartInfo.UseShellExecute = True

    process = System.Diagnostics.Process.Start(processStartInfo)

1 个答案:

答案 0 :(得分:0)

行。问题似乎是cmd.exe根据它们是否包含引号字符来区别对待它的参数。绕过这个。我直接调用cmd.exe而不是使用ShellExecute,并用引号括起整个命令。

Dim script As String = My.Application.Info.DirectoryPath & "\Test.bat"
RunCommand(script, """a quoted string""", "string2")

Private Function RunCommand(Script As String, ParamArray Parameters() As String) As Boolean

    Dim process As System.Diagnostics.Process = Nothing
    Dim processStartInfo As System.Diagnostics.ProcessStartInfo
    Dim OK As Boolean

    processStartInfo = New System.Diagnostics.ProcessStartInfo()
    processStartInfo.FileName = """" & Environment.SystemDirectory & "\cmd.exe" & """"

    If My.Computer.Info.OSVersion >= "6" Then  ' Windows Vista or higher
        ' required to invoke UAC
        processStartInfo.Verb = "runas"
    End If

    processStartInfo.Arguments = "/C """"" & Script & """ " & Join(Parameters, " ") & """"
    processStartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal
    processStartInfo.UseShellExecute = False

    'MsgBox("About to execute the following command:" & vbCrLf & processStartInfo.FileName & vbCrLf & "with parameters:" & vbCrLf & processStartInfo.Arguments)
    Try
        process = System.Diagnostics.Process.Start(processStartInfo)
        OK = True
    Catch ex As Exception
        MsgBox(ex.ToString, MsgBoxStyle.Exclamation, "Unexpected Error running update script")
        OK = False
    Finally
        If process IsNot Nothing Then
            process.Dispose()
        End If
    End Try

    Return OK

End Function