dark9duck
dark9duck

Reputation: 13

How to pass the name of environment variable as an argument?

I have a batch.bat with one input argument %1. I want to start the script as: batch.bat PATH. I would like this to display the PATH environment variable with echo.

I tried:

@echo %1
E:\>batch.bat PATH
PATH

but I would like to have the content of PATH environment variable.

E:\>batch.bat PATH
C:\Windows;   

Upvotes: 0

Views: 100

Answers (1)

user6811411
user6811411

Reputation:

You need delayed expansion to output a variable referenced by a cmd line argument.
This batch uses two different methods for this,

  • a pseudo call with doubled percent signs (which forces the parser to evaluate the line twice, on first pass reducing two %% to one in 2nd pass the other vars are already expanded) and
  • using the ! instead the normal single percent sign with a prior command setlocal enabledelayedexpansion

:: Q:\Test\2018\05\10\SO_50280684.cmd
@Echo off&SetLocal EnableDelayedExpansion
Echo(%1
Echo(!%1!
Call Echo(%%%1%%

I use the command separator ( instead off a space to suppress an Echo is off message incase of an empty var.

Sample with command

>SO_50280684.cmd PROCESSOR_ARCHITECTURE
PROCESSOR_ARCHITECTURE
AMD64
AMD64

Upvotes: 3

Related Questions