简体   繁体   中英

How to pass arguments when executing environment variable in Powershell?

I'm trying to pass named arguments to a batch file referred to using environment variables in Windows. The environment variable is a direct path to the .bat file, and can easily be executed in Powershell using $env:MY_VAR which promptly prints the full path to the batch. However if I attempt to pass arguments Powershell will complain about unexpected tokens. What I tried was:

$env:MY_VAR -data some_data.txt -other more_data.txt

$env:MY_VAR --data some_data.txt --other more_data.txt

$env:MY_VAR --data=some_data.txt --other=more_data.txt

$env:MY_VAR -data=some_data.txt -other=more_data.txt

and many more ... I also tried encapsulating my values in quotes in case it was something to do with their naming. None of these worked, but if I were to use the direct path as such:

FULL_PATH/program.bat -data some_data.txt -other more_data.txt

it will work just fine. Does Powershell interpret environment variables in some particular way that requires argument passing to be done differently? My Google searches does not yield any useful results, and it is mostly people trying to start Powershell from within a batch script... Not exactly what I'm looking for. I've also come across extensions for Powershell, but that just seemed like an odd solution.

Any help is welcome and appreciated.

You need to use the & invocation operator to tell powershell that the string you are passing is a command to invoke:

& $env:MY_VAR -data some_data.txt -other more_data.txt

For more details see this page .

Environment variables are just a string. If you want to execute what's in your variable you first need to tell PowerShell that's what you want. In order to do that, you can use & .

& $env:MY_VAR some_data.txt more_data.txt

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM