DOS Command Class for VBScript

DOS is one of those handy things that in a technical sense you never quite seem to get away from.  The command line often allows you to do things quicker than the over designed graphical options and sometimes simply allow you to do things that there isn’t another option for.

Because I sometimes want access to command line utilities and more importantly their output within VBScript I’ve scripted a class to allow me to take advantage of this.  The script below demonstrates some simple ways in which to use this command.  But be careful when outputting anything you might want to view as you may need to manage large amounts of text which a MsgBox might not be able to handle.

Option Explicit

'Sample commands
ExecCmd "time /t"
ExecCmd "dir c:\"
ExecCmd "set"

Sub ExecCmd(p_strDOSCmd)
    'This function is just a display wrapper really.
    'All the neat stuff is in the clsDOSCommandExecutor class
    Dim objCommand
    Set objCommand = New clsDOSCommandExecutor

    msgbox objCommand.GetOutput, , p_strDOSCmd
End Sub

Class clsDOSCommandExecutor
    Dim objShell, objExec
    Dim strCommand
    Dim strError
    Dim objError
    Dim objOutput
    Dim strOutput

    Sub ExecuteCommand(p_strCommand)
        strCommand = "cmd /c " & p_strCommand
        Set objShell = CreateObject("Wscript.Shell" )


        Set objExec = objShell.Exec(strCommand)

        Do Until objExec.Status
            Wscript.Sleep 200

        Set objError = objExec.StdErr
        strError = objError.ReadAll

        Set objOutput = objExec.stdOut
        strOutput = objOutput.ReadAll
    End Sub

    Function GetOutput()
        GetOutput = strOutput
    End Function

    Function GetError()
        GetError = strError
    End Function

    Function Failed()
        If strError = "" Then
            Failed = false
            Failed = true
        End If
    End Function
End Class
Author: Stephen Millard
Tags: | shell | vbs |

Buy me a coffeeBuy me a coffee

Related posts that you may also like to read