Search
« Skype and Web Servers | Main | VBScript and Getting the Message Across »
Sunday
Aug092009

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

    objCommand.ExecuteCommand(p_strDOSCmd)
    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" )

        objShell.Exec(strCommand)

        Set objExec = objShell.Exec(strCommand)

        Do Until objExec.Status
            Wscript.Sleep 200
        Loop

        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
        Else
            Failed = true
        End If
    End Function
End Class

PrintView Printer Friendly Version

EmailEmail Article to Friend

Reader Comments

There are no comments for this journal entry. To create a new comment, use the form below.

PostPost a New Comment

Enter your information below to add a new comment.
Author Email (optional):
Author URL (optional):
Post:
 
Some HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>