Page 1 of 1

Absolute path of file located in %PATH%

Posted: Mon Feb 02, 2009 6:21 am
by Mistrel
There is a bug with Windows batch files where if you call a batch file in quotes that is located in a %PATH% directory it won't be able to retrieve its local directory using %~dp0.

I wrote a batch script to parse %PATH% to reestablish its location but it was very slow. So I wrote something better in PureBasic. :)

envpath.pb

Code: Select all

;/***********************************************************************
;/* Program: envpath (Get the first matching absolute path of the
;/*                    filename parameter from the environment variable
;/*                    %PATH%)
;/* Summary: 
;/*    This tool will check each string field in the environment variable
;/*    %PATH% using the delimiter ';' for the first instance of the
;/*    absolute path of the filename passed as the first parameter.
;/* Compiler options:
;/*    Compile as a console program. 
;/************************************************************************/

OpenConsole()

HelpText.s=#CRLF$+"Get the first matching absolute path of the filename parameter from"
HelpText.s+#CRLF$+"the environment variable."
HelpText.s+#CRLF$+""
HelpText.s+#CRLF$+"ENVPATH [FileName]"
HelpText.s+#CRLF$+""
HelpText.s+#CRLF$+"  FileName     Specifies the name of the file to search for"
HelpText.s+#CRLF$+""

If Not CountProgramParameters()
  ;/ Print help text if no parameters exist
  Print(HelpText.s)
Else
  ;/ File to locate
  FileName.s=ProgramParameter()
  
  ;/ Get %PATH% string
  GetEnvironmentVariable_(@"PATH",@PathString.s{8191},8191)
  
  ;/ Add trailing delimiter for string field function
  If Not Right(PathString.s,1)=";"
    PathString.s+";"
  EndIf
  
  For i=1 To CountString(PathString.s,";")
    ;/ Check all string fields using the semi-colon ASCII character as a delimiter
    ParamField.s=StringField(PathString.s,i,";")
    
    ;/ Confirm that each path has a trailing slash
    If Not Right(ParamField.s,1)="\"
      ParamField.s+"\"
    EndIf
    
    ;/ Parameter is a path and the file exists at this path
    If FileSize(ParamField.s)=-2 And FileSize(ParamField.s+FileName.s)>=0
      Print(ParamField.s)
      Break
    EndIf
  Next i
EndIf

End