2014-09-18 58 views
0

我想从我的Vb.Net应用程序运行批处理文件。 VS 2010 targetting .Net 4.从.Net调用的批处理文件不运行

它在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) 
+0

将“暂停”添加到.bat文件的末尾,以便您可以阅读错误消息。永远不要忘记检查Process.ExitCode,以便诊断完整的故障。 – 2014-09-18 16:34:30

+0

@Hans正如我在问题中所述,我用单个暂停命令替换了整个批处理文件,但该窗口立即消失。 我也许可以尝试查看Process.ExitCode,但我假设正在显示命令窗口(尽管非常简短),该过程看起来开始OK。我不希望我的代码等待进程完成,尽管我可能暂时为了调试目的而这样做。 – 2014-09-18 16:42:25

+0

如果您重命名.bat以使其找不到,那么Process.Start应抛出“找不到文件”异常。这是否发生? – 2014-09-18 17:02:00

回答

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