2012-02-01 128 views
1

我想通过VB运行一个批处理文件,我需要等待它完成/退出前进度。我相信我遇到的问题是,当执行批处理文件时,它会打开cmd.exe而不是批处理文件。在继续之前等待批处理文件关闭 - VB.net

这是我用VB

 My.Computer.FileSystem.DeleteFile(My.Application.Info.DirectoryPath & "\PingCheck\machines.txt") 
    FileCopy(My.Application.Info.DirectoryPath & "\machines.txt", My.Application.Info.DirectoryPath & "\PingCheck\machines.txt") 

    Dim psi As New ProcessStartInfo(My.Application.Info.DirectoryPath & "\PingCheck\go.bat") 
    psi.RedirectStandardError = True 
    psi.RedirectStandardOutput = True 
    psi.CreateNoWindow = False 
    psi.WindowStyle = ProcessWindowStyle.Hidden 
    psi.UseShellExecute = False 

    Dim process As Process = process.Start(psi) 
    process.WaitForExit() 

    ProgressBar1.Value = ProgressBar1.Value + 2 
    FileCopy(My.Application.Info.DirectoryPath & "\PingCheck\machines.txt", My.Application.Info.DirectoryPath & "\machines.txt") 
    'My.Computer.FileSystem.DeleteFile(My.Application.Info.DirectoryPath & "\ping.bat") 
    MsgBox("Ping Check Complete") 

遇到的问题即时执行的是,它会直接删除ping.bat完成之前。
如何从我调用的批处理文件中监控进程。然后一旦退出,继续使用脚本?

回答

2

RHicke显示了如何在VB.NET这里,Run batch file in vb.net?运行一个批处理过程中很好的例子。

要展开,您应该使用函数WaitForExit()等待该过程完成。

Dim psi As New ProcessStartInfo("Path TO Batch File") 
psi.RedirectStandardError = True 
psi.RedirectStandardOutput = True 
psi.CreateNoWindow = False 
psi.WindowStyle = ProcessWindowStyle.Hidden 
psi.UseShellExecute = False 

Dim process As Process = Process.Start(psi) 

process.WaitForExit() 
+0

谢谢,但我不相信这是工作。 我已经调整了我的脚本来匹配这个,但它仍然显示MessageBox之前它似乎已经完成。看到第一篇文章 – K20GH 2012-02-01 13:17:20

+0

为什么不呢?你认为哪部分不起作用? – 2012-02-01 13:19:05

+0

我告诉它运行\ PingCheck \ go.bat,并在它完成之前显示消息框。 go.bat实际上运行并设置了一个ping测试循环,所以它不会关闭,直到这些完成 – K20GH 2012-02-01 13:22:19

1

您可以使用System.Diagnostics.Process类来启动批处理文件。流程参考将使您可以访问财产HasExited(和更多有趣的信息)。 HasExited属性指示进程是否已完成。

var process = System.Diagnostics.Process.Start(new ProcessStartInfo 
           { 
            FileName = "batch file path", 
            RedirectStandardError = true, 
            RedirectStandardOutput = true, 
            UseShellExecute = false, 
            Arguments = "parameters if applicable", 
            CreateNoWindow = true 
           }); 

while(!process.HasExited) 
{ 
    // obviously do some clever here to wait 
}  

代码是在C#中,但原则应该在VB.NET

工作
0

我以前做过类似的事情。该代码使用System.Diagnostics.Process(由rivethead_提及)从VB.Net中调用RoboCopy。

Dim proc As System.Diagnostics.Process = New System.Diagnostics.Process() 

proc.EnableRaisingEvents = False 
proc.StartInfo.FileName = "d:\robocopy\robocopy" 
proc.StartInfo.Arguments = strSrcDir & " " & strDestDir & " " & strFile & " " & My.Settings.robocopyFlags 
proc.Start() 
proc.WaitForExit() 

否则,ping.bat在干什么?它只是做一个“ping”命令?如果是这样,也许你可以用System.Diagnostics.Process调用它(而不是调用一个.bat文件来做到这一点)。这可能会让您对流程有更多的控制权。

+0

ping.bat实际上会自行循环,因此我相信可能发生的情况是原始ping.bat在打开另一个副本后关闭。由于我没有写入批处理文件,而且它非常复杂,我无法告诉:( – K20GH 2012-02-01 13:47:08

相关问题