Home > Blockchain >  Execute a bat file with a variable name in the path
Execute a bat file with a variable name in the path

Time:04-30

I am having a problem executing a powershell script where I want to point to different versions of a bat file based on some arguments

Hard coding the path as follows works with no issues:

    & 'C:\Program Files\MATLAB\R2022a\bin\mcc.bat'  -W $command -T link:exe  ...

but replacing a folder name with a variable causes it to fail:

    $Matlab_version = "R2022a"
    & 'C:\Program Files\MATLAB\$Matlab_version\bin\mcc.bat'  -W $command -T link:exe

with the following output:

 & : The term 'C:\Program Files\MATLAB\%$Matlab_version%\bin\mcc.bat' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:3
  & 'C:\Program Files\MATLAB\%$Matlab_version%\bin\mcc.bat'  -W $comman ...

I've tried even creating a variable with the path name

$mcc_loc = & 'C:\Program Files\MATLAB\$Matlab_version\bin\mcc.bat'
Write-Host $mcc_loc

which produces a string with the correct path. Any help is greatly appreciated. My dumb solution is to have an if statement for each $Matlab_version and hard code it in there but I'm sure there has to be a more elegant solution

CodePudding user response:

It's because you are using single quotation marks.

variables will not be interpreted within single marks, everything will be taken as a literal string.

use double quotes instead when passing in variables mid string.

example: quotes in action

CodePudding user response:

You need to change the single quote ' to double quote "

Double-quoted strings A string enclosed in double quotation marks is an expandable string. Variable names preceded by a dollar sign ($) are replaced with the variable's value before the string is passed to the command for processing.

$Matlab_version = "R2022a"
& "C:\Program Files\MATLAB\$Matlab_version\bin\mcc.bat"  -W $command -T link:exe

See about_Quoting_Rules

  • Related