简体   繁体   English

在VB.net中获取shell命令的输出

[英]Get the output of a shell Command in VB.net

I have a VB.net program in which I call the Shell function. 我有一个VB.net程序,我在其中调用Shell函数。 I would like to get the text output that is produced from this code in a file. 我想从文件中获取从此代码生成的文本输出。 However, this is not the return value of the executed code so I don't really know how to. 但是,这不是执行代码的返回值,所以我真的不知道如何。

This program is a service but has access to the disk no problem as I already log other information. 这个程序是一个服务,但可以访问磁盘没有问题,因为我已经记录了其他信息。 The whole service has multiple threads so I must also make sure that when the file is written it's not already accessed. 整个服务有多个线程,所以我还必须确保在写入文件时它尚未被访问。

You won't be able to capture the output from Shell. 您将无法捕获Shell的输出。

You will need to change this to a process and you will need to capture the the Standard Output (and possibly Error) streams from the process. 您需要将其更改为进程,并且需要从进程中捕获标准输出 (可能还有错误)流。

Here is an example: 这是一个例子:

        Dim oProcess As New Process()
        Dim oStartInfo As New ProcessStartInfo("ApplicationName.exe", "arguments")
        oStartInfo.UseShellExecute = False
        oStartInfo.RedirectStandardOutput = True
        oProcess.StartInfo = oStartInfo
        oProcess.Start()

        Dim sOutput As String
        Using oStreamReader As System.IO.StreamReader = oProcess.StandardOutput
            sOutput = oStreamReader.ReadToEnd()
        End Using
        Console.WriteLine(sOutput)

To get the standard error: 要获得标准错误:

'Add this next to standard output redirect
 oStartInfo.RedirectStandardError = True

'Add this below
Using oStreamReader As System.IO.StreamReader = checkOut.StandardError
        sOutput = oStreamReader.ReadToEnd()
End Using

Just pipe the output to a text file? 只需将输出传输到文本文件?

MyCommand > "c:\file.txt"

Then read the file. 然后读取文件。

    Dim proc As New Process

    proc.StartInfo.FileName = "C:\ipconfig.bat"   
    proc.StartInfo.UseShellExecute = False
    proc.StartInfo.RedirectStandardOutput = True
    proc.Start()
    proc.WaitForExit()

    Dim output() As String = proc.StandardOutput.ReadToEnd.Split(CChar(vbLf))
    For Each ln As String In output
        RichTextBox1.AppendText(ln & vbNewLine)
        lstScan.Items.Add(ln & vbNewLine)
    Next

======================================================================= create a batch file in two lines as shown below: ================================================== =====================在两行中创建一个批处理文件,如下所示:

    echo off
    ipconfig

' make sure you save this batch file as ipconfig.bat or whatever name u decide to pick but make sure u put dot bat at the end of it. '确保将此批处理文件保存为ipconfig.bat或您决定选择的任何名称,但请确保将dot bat放在其末尾。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM