Retrieving Command Line Parameters

Getting command line parameters or seeing if they are present is not as easy as you would think. I whipped up some code to make this flexible and easy.

   Private Const ParameterPrefix As Char = "/"c
       
   Private Function GetCommandLineArgument(ByVal parameter As String) As String
      Dim paramValue = String.Empty
      For Each tempValue As String In System.Environment.GetCommandLineArgs
         If tempValue.Contains(ParameterPrefix + parameter + "=") Then
            paramValue = tempValue.Split(Char.Parse("="))(1).ToString().Trim()
            Exit For
         End If
      Next
      Return paramValue
   End Function
   Private Function CommandLineArgumentExists(ByVal parameter As String) As Boolean
      Dim exists = False
      For Each tempValue As String In System.Environment.GetCommandLineArgs
         If tempValue.Contains(ParameterPrefix + parameter) Then
            exists = True
            Exit For
         End If
      Next
      Return exists
   End Function
   Private Function GetCommandLineArgument(ByVal parameter As String, ByVal prefix As String) As String
      Dim paramValue = String.Empty
      For Each tempValue As String In System.Environment.GetCommandLineArgs
         If tempValue.Contains(prefix + parameter + "=") Then
            paramValue = tempValue.Split(Char.Parse("="))(1).ToString().Trim()
            Exit For
         End If
      Next
      Return paramValue
   End Function
   Private Function CommandLineArgumentExists(ByVal parameter As String, ByVal prefix As String) As Boolean
      Dim exists = False
      For Each tempValue As String In System.Environment.GetCommandLineArgs
         If tempValue.Contains(prefix + parameter) Then
            exists = True
            Exit For
         End If
      Next
      Return exists
   End Function

Usage:

 Debug.WriteLine(CommandLineArgumentExists("source"))
 Debug.WriteLine(GetCommandLineArgument("source", "-"))

Tip Submitted By: David McCarter

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s