Windows Bat 文件可选参数解析 [英] Windows Bat file optional argument parsing

查看:36
本文介绍了Windows Bat 文件可选参数解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要我的 bat 文件接受多个可选的命名参数.

I need my bat file to accept multiple optional named arguments.

mycmd.bat man1 man2 -username alice -otheroption

例如我的命令有 2 个强制参数和两个可选参数 (-username),其参数值为 alice 和 -otheroption:

For example my command has 2 mandatory parameters, and two optional parameters (-username) that has an argument value of alice, and -otheroption:

我希望能够将这些值提取到变量中.

I'd like to be able to pluck these values into variables.

只是给已经解决了这个问题的任何人打个电话.伙计,这些 bat 文件很痛苦.

Just putting out a call to anyone that has already solved this. Man these bat files are a pain.

推荐答案

虽然我倾向于同意 @AlekDavis 的评论,不过在 NT shell 中有几种方法可以做到这一点.

Though I tend to agree with @AlekDavis' comment, there are nonetheless several ways to do this in the NT shell.

我将利用 SHIFT 命令和 IF 条件分支,类似这样...

The approach I would take advantage of the SHIFT command and IF conditional branching, something like this...

@ECHO OFF

SET man1=%1
SET man2=%2
SHIFT & SHIFT

:loop
IF NOT "%1"=="" (
    IF "%1"=="-username" (
        SET user=%2
        SHIFT
    )
    IF "%1"=="-otheroption" (
        SET other=%2
        SHIFT
    )
    SHIFT
    GOTO :loop
)

ECHO Man1 = %man1%
ECHO Man2 = %man2%
ECHO Username = %user%
ECHO Other option = %other%

REM ...do stuff here...

:theend

这篇关于Windows Bat 文件可选参数解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆