Jump to content

Script with infinite command line parameters


Recommended Posts

So I've finally completed my first legitimate script (yay!), and I'd say it's about 90% done. In a nutshell, it's designed to be called from a button within Access via a macro, and it backs up the database when the user exits their switchboard (clicking the "Exit & Backup" button).

I originally stored all of the information regarding the filename/folder/etc. within the script itself. I then realized it'd be a major PITA to use it for multiple databases, so I was able to get all of this information from an INI file. The script searches for an INI file in the same directory as the script with the same filename, and if it doesn't find one it creates one based on user input. It then reads from the INI file and backs up the database accordingly based on whatever values are in there (location of the folder, name of the file, number of backups to keep, and title of the file).

I was so giddy when I got this all working. But then I realized, I'd need a script and a corresponding INI for each database that gets backed up. Ack!

So I'm wondering, is it possible to create infinite command line parameters, or something of the like? I'm thinking the button in Access would run "backupdatabase.exe /ininame.ini". The script would then look for that INI file in the script directory, and gather the correct values.

Any suggestions for how to tackle this problem?

Thanks!

Link to comment
Share on other sites

I am not sure what the limitation within AutoIt is in terms of how many command line parameters it can take, but I am guessing that it would be limited to how large an array can be created in terms of elements.

You can use the $CmdLine variable to catch any parameters passed to the executable. You can look it up in the help file.

It is used as $CmdLine[0] finds how many parameters are passed to the program, then each successive element is going to be each parameter passed.

ex. - program.exe param1 param2 ...

In this case:

$CmdLine[0] ;would return 2
$CmdLine[1] ;would return param1
$CmdLine[2] ;would return param2

Hope this helps...muttley

[font="Verdana"]People who say it cannot be done should not interrupt those who are doing it. - George Benard Shaw[/font]

Link to comment
Share on other sites

Thanks for the uber-quick reply.

I've been up and down the help file for command line parameters, and I find it to be kind of sparse when compared with the rest of the documentation. I've been unable to glean anything more than just the basics from it. I've successfully created "defined" parameters, such as running script.exe /help to pop open a text file and things like that. But in terms of a creating a parameter that changes based on what INI file the script should read from, I'm still at a loss.

Link to comment
Share on other sites

Thanks for the uber-quick reply.

I've been up and down the help file for command line parameters, and I find it to be kind of sparse when compared with the rest of the documentation. I've been unable to glean anything more than just the basics from it. I've successfully created "defined" parameters, such as running script.exe /help to pop open a text file and things like that. But in terms of a creating a parameter that changes based on what INI file the script should read from, I'm still at a loss.

Something like this?
Global $sIniFile

; YourScript.exe /ini "C:\Temp\YourIniFile.ini"
For $n = 1 To $CmdLine[0] - 1
    If $CmdLine[$n] = "/ini" Then
        $sIniFile = $CmdLine[$n + 1]
        ExitLoop
    EndIf
Next

muttley

Valuater's AutoIt 1-2-3, Class... Is now in Session!For those who want somebody to write the script for them: RentACoder"Any technology distinguishable from magic is insufficiently advanced." -- Geek's corollary to Clarke's law
Link to comment
Share on other sites

i wrote a function to get "multiple commandline parameters with parameter definition" - maybe you can use it

it may be not as elegant as the _getopt(), but it suits MY needs :-)

call with "exename -Betriebsart TEST -QuellDateiName temp.txt"

GLOBAL $cmdline_old = $CmdLineRaw

Global $betriebsart = _ReadCmdLine("Betriebsart");

Global $quelldateiname = _ReadCmdLine("QuellDateiName");







;
Func _ReadCmdLine($switch)
    If $CmdLine[0] > 0 Then

    ; vorne ein leerzeichen hin sonst blickt er das erste " -" nicht..
        $CmdLineRaw = "  " & $CmdLineRaw;

        $CmdLineRaw = StringReplace($CmdLineRaw, " -", "|"); options are separated by "-"

    ; so nun sind die optionen mit "|" getrennt
        $Cmdopt = StringSplit($CmdLineRaw, "|"); options are separated by "-"
    ;_ArrayDisplay($Cmdopt, "options")

    ; start with 2
        For $I = 2 To UBound($Cmdopt) - 1;

        ; $param = StringLeft($Cmdopt[$I], 1); "f" - 1 char
        ;
        ; der parameter sollte bis zum nächsten " " gehen (leerzeichen)

            $p = StringInStr($Cmdopt[$I], ' ');
            $param = StringLeft($Cmdopt[$I], $p)
            $param = StringStripWS($param, 3);


        ; value is now rest of switch
            $value = StringRight($Cmdopt[$I], StringLen($Cmdopt[$I]) - $p); take rest as value
            $value = StringStripWS($value, 3);

        ; found it ??
            If $param = $switch And $value <> "" Then
                
                $value = StringReplace($value, '"', ""); ersetze " zeichen
                
                Return $value
            EndIf; value F?


        Next; all params
    EndIf

    Return ""; default
EndFunc  ;==>_ReadCmdLine
Link to comment
Share on other sites

Something like this?

Global $sIniFile

; YourScript.exe /ini "C:\Temp\YourIniFile.ini"
For $n = 1 To $CmdLine[0] - 1
    If $CmdLine[$n] = "/ini" Then
        $sIniFile = $CmdLine[$n + 1]
        ExitLoop
    EndIf
Next

muttley

Posted Image

So simple, Occam's razor wins again. Thanks!

Link to comment
Share on other sites

Here's what I have for the command line parameters. Everything seems to work A-ok, although admittedly I have no idea if this is considered correct. I'm relatively new to AutoIt, and for that matter, programming in general.

Global $sIniFile
Global $var
If $cmdline[0] > 0 Then $Var = $Cmdline [1]

Select
    Case $Var = ''
        MsgBox(0, "", "No switch entered")
        Exit
    Case $Var = "/edit"
        Local $inierror = "An unexpected error occured. Please contact your administrator."
        Local $readini = FileOpenDialog("Please select the INI to edit", @ScriptDir, "INI files (*.ini)")
        Local $readinidir = IniRead($readini, "Backup", "sourcedir", $inierror)
        Local $readininame = IniRead($readini, "Backup", "sourcename", $inierror)
        Local $readininum = IniRead($readini, "Backup", "maxcount", $inierror)
        Local $readinititle = IniRead($readini, "Backup", "title", $inierror)
        Local $writeinichanged = FileOpenDialog("Please locate the file", $readinidir, "All files (*.*)")
        Local $szDriveFileEdit, $szDirFileEdit, $szFNameFileEdit, $szExtFileEdit 
        Local $fileinipathedit = _PathSplit($writeinichanged, $szDriveFileEdit, $szDirFileEdit, $szFNameFileEdit, $szExtFileEdit)
        Local $fileiniedit = $fileinipathedit[1] & $fileinipathedit[2]
        Local $filefolderlenedit = StringLen($fileiniedit)
        Local $filefolderedit = StringLeft($fileiniedit, $filefolderlenedit - 1)
        Local $filefoldernameedit = $fileinipathedit[3] & $fileinipathedit[4]   
        Local $writeininum = InputBox("How many backups?", "Please enter a number from 1 to 50", $readininum, " M2", 250, 125)
        Local $writeinititle = InputBox("Title", "Please enter the title of the file", $readinititle, " M", 250, 125)   
        IniWrite($readini, "Backup", "sourcedir", $filefolderedit)
        IniWrite($readini, "Backup", "sourcename", $filefoldernameedit)
        IniWrite($readini, "Backup", "maxcount", $writeininum)
        IniWrite($readini, "Backup", "title", $writeinititle)
        Exit
    Case $Var = "/create"
        Local $sourceinifile = FileOpenDialog("Please select the file to be backed up", "C:\", "All files (*.*)")
        Local $titleini = InputBox("Title", "Please enter the title of the file", "", " M", 250, 125)
        Local $shorttitle = StringStripWS($titleini, 8)
        Local $maxcountini = InputBox("How many backups?", "Please enter a number from 1 to 50", "5", " M2", 250, 125)  
    ; Code below will split the file selected above into the directory and the filename
        Local $szDriveFile, $szDirFile, $szFNameFile, $szExtFile 
        Local $fileinipath = _PathSplit($sourceinifile, $szDriveFile, $szDirFile, $szFNameFile, $szExtFile)
        Local $fileini = $fileinipath[1] & $fileinipath[2]
        Local $filefolderlen = StringLen($fileini)
        Local $filefolder = StringLeft($fileini, $filefolderlen - 1)
        Local $filefoldername = $fileinipath[3] & $fileinipath[4]
        Local $newinipath = @ScriptDir & "\" & $shorttitle & ".ini"
    ; Pass the values from above into the INI
        IniWrite($newinipath, "Backup", "sourcedir", $filefolder)
        IniWrite($newinipath, "Backup", "sourcename", $filefoldername)
        IniWrite($newinipath, "Backup", "title", $titleini)
        IniWrite($newinipath, "Backup", "maxcount", $maxcountini)
        msgbox(0, "Success", "This file can now be backed up. Run backup.exe /ini " & $shorttitle & ".ini")
        Exit
    Case $var = "/ini"
        For $n = 1 To $CmdLine[0] - 1
            If $CmdLine[$n] = "/ini" Then
                $sIniFile = $CmdLine[$n + 1]
                ExitLoop
            EndIf
        Next
    Case Else
        MsgBox(0, "", "That's not a valid switch, doofus.")
EndSelect

There are a few minor bugs unrelated to the parameters that I'm trying to figure out (i.e. have a quote display in a MsgBox, validate the data entered in an InputBox so it will only accept numbers, and require that a file be selected in FileOpenDialog before continuing). But other than that everything seems to be working good. Hopefully I haven't made any major mistakes.

Link to comment
Share on other sites

i wrote a function to get "multiple commandline parameters with parameter definition" - maybe you can use it

it may be not as elegant as the _getopt(), but it suits MY needs :-)

call with "exename -Betriebsart TEST -QuellDateiName temp.txt"

Nice, but it can be done with RegExp more quickly, and i think even more effective, here is what i use:

;Example on how to get unknown Command Line...

;If $CmdLine[0] = 0 Then Exit ;Exit the script, because the command line was empty ;)

;Just for the demo
If $CmdLine[0] = 0 Then $CmdLineRaw = '-File "C:\Program Files\File.txt" /URL "http://google.com"'

MsgBox(64, "", _
    _GetCmdLine($CmdLineRaw, "-File") & @LF & _
    _GetCmdLine($CmdLineRaw, "/URL"))

Func _GetCmdLine($sCmdLine, $sArgument)
    Local $sRetCmd = StringRegExpReplace($sCmdLine, '(?i).*?' & $sArgument & '( |)("|)(.*?)("|)( /| -|$).*?$', '\3')
    
    Return StringStripWS($sRetCmd, 3)
EndFunc

 

Spoiler

Using OS: Win 7 Professional, Using AutoIt Ver(s): 3.3.6.1 / 3.3.8.1

AutoIt_Rus_Community.png AutoIt Russian Community

My Work...

Spoiler

AutoIt_Icon_small.pngProjects: ATT - Application Translate Tool {new}| BlockIt - Block files & folders {new}| SIP - Selected Image Preview {new}| SISCABMAN - SciTE Abbreviations Manager {new}| AutoIt Path Switcher | AutoIt Menu for Opera! | YouTube Download Center! | Desktop Icons Restorator | Math Tasks | KeyBoard & Mouse Cleaner | CaptureIt - Capture Images Utility | CheckFileSize Program

AutoIt_Icon_small.pngUDFs: OnAutoItErrorRegister - Handle AutoIt critical errors {new}| AutoIt Syntax Highlight {new}| Opera Library! | Winamp Library | GetFolderToMenu | Custom_InputBox()! | _FileRun UDF | _CheckInput() UDF | _GUIInputSetOnlyNumbers() UDF | _FileGetValidName() UDF | _GUICtrlCreateRadioCBox UDF | _GuiCreateGrid() | _PathSplitByRegExp() | _GUICtrlListView_MoveItems - UDF | GUICtrlSetOnHover_UDF! | _ControlTab UDF! | _MouseSetOnEvent() UDF! | _ProcessListEx - UDF | GUICtrl_SetResizing - UDF! | Mod. for _IniString UDFs | _StringStripChars UDF | _ColorIsDarkShade UDF | _ColorConvertValue UDF | _GUICtrlTab_CoverBackground | CUI_App_UDF | _IncludeScripts UDF | _AutoIt3ExecuteCode | _DragList UDF | Mod. for _ListView_Progress | _ListView_SysLink | _GenerateRandomNumbers | _BlockInputEx | _IsPressedEx | OnAutoItExit Handler | _GUICtrlCreateTFLabel UDF | WinControlSetEvent UDF | Mod. for _DirGetSizeEx UDF
 
AutoIt_Icon_small.pngExamples: 
ScreenSaver Demo - Matrix included | Gui Drag Without pause the script | _WinAttach()! | Turn Off/On Monitor | ComboBox Handler Example | Mod. for "Thinking Box" | Cool "About" Box | TasksBar Imitation Demo

Like the Projects/UDFs/Examples? Please rate the topic (up-right corner of the post header: Rating AutoIt_Rating.gif)

* === My topics === *

==================================================
My_Userbar.gif
==================================================

 

 

 

AutoIt is simple, subtle, elegant. © AutoIt Team

Link to comment
Share on other sites

RegEx are definately a smart way to go. Smarter than my knowledge. My approach would be to make a string that consists of all the parameters than use either regex, or stringinstr against the whole thing. May not be the best way, but that's just the perspective of a novice.

Link to comment
Share on other sites

RegEx are definately a smart way to go. Smarter than my knowledge. My approach would be to make a string that consists of all the parameters than use either regex, or stringinstr against the whole thing. May not be the best way, but that's just the perspective of a novice.

If you must go that route, you would be working with $CmdLineRaw. This variable already contains the entire calling command line parameters, unsplit.

muttley

Valuater's AutoIt 1-2-3, Class... Is now in Session!For those who want somebody to write the script for them: RentACoder"Any technology distinguishable from magic is insufficiently advanced." -- Geek's corollary to Clarke's law
Link to comment
Share on other sites

If you must go that route, you would be working with $CmdLineRaw. This variable already contains the entire calling command line parameters, unsplit.

muttley

Good to know. :)
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...