Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
252 views
in Technique[技术] by (71.8m points)

batch file - How do I correctly use a path as a parameter?

I am trying to change the directory running a bat file with this parameter that will check if this directory exists, make sure it's not a file and change the working directory to it.

@ECHO OFF

IF NOT "%1"=="" (
    IF EXIST %1 (
        IF EXIST %1NUL (
            CD %1
        ) ELSE (
            ECHO Warning: Parameter path is incorrect . . .
        )
    ) ELSE (
        ECHO Warning: Given path does not exist ...
    )
) ELSE (
    ECHO Info: No parameters are given . . .
)

ECHO Info: %CD% is current directory . . .

The problem is that when I try to run this with CMD and put the parameter in the quote I get path does not exist error, and if I run this batch file without any parameters it gives me a syntax error.

question from:https://stackoverflow.com/questions/65937651/how-do-i-correctly-use-a-path-as-a-parameter

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As a supplement to my earlier comments, (which should solve your reported issue), here's an alternative methodology:

@Echo Off
Verify 1 2> NUL
SetLocal EnableExtensions
If ErrorLevel 1 (Echo ERROR: Could not enable extensions.
    GoTo PressClose)
If "%~1" == "" (Echo ERROR: No input argument received.
    GoTo InputError) Else For %%G In ("%~1") Do If "%%~aG" Lss "d" (
    If "%%~aG" GEq "-" (Echo ERROR: Input argument is a file.
        GoTo InputError
    ) Else (Echo ERROR: Your input argument could not be found.
        GoTo InputError))
Rem === Your code here ===
CD /D %1
Set /P "=Your current directory is: %CD%" 0< NUL & Echo(
Rem === Code ends here ===
GoTo PressClose

:InputError
Echo This script requires an existing directory as input.

:PressClose
Echo Please press a key to exit this script.
Pause 1> NUL
Exit /B

You would obviously just insert your code in between the two Remarks, I've included two lines there, for the purpose of showing you that it worked, you are of course free to adjust those as necessary


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...