I want to save a PowerSell command in a variable and execute in a cmd Problem : get current path with exe file using command : $(get-location).Path
I try this but not working :
Set $path = powershell -Command $(get-location).Path
echo "$path"
Try for similar command line, Note we need to escape the first ) using ^)
C:\Users\K\Desktop>for /f "delims=" %c in ('powershell -Command $(get-location^).Path') do @set "$path=%c"
C:\Users\K\Desktop>echo %$path%
C:\Users\K\Desktop
C:\Users\K\Desktop>
so in a batch file use
for /f "delims=" %%c in ('powershell -Command $(get-location^).Path') do @set "$path=%%c"
echo %$path%
However there are many much simpler ways to find the current directory.
As suggested avoid any variable name that is very similar to "path" such as $path since it may be misunderstood by a downstream app stripping $, but the simplest way at cmd level would be to use the %cd% value:-
C:\Users\K\Desktop>set "ExDir=%cd%" & echo %ExDir%
C:\Users\K\Desktop
C:\Users\K\Desktop>
In a batch file it is common to use pushd and popd with a stored %~dp0 however at command line popd may not have a directory stack to return to, thus this method can be used.
C:\Users\K\Desktop>set "PopDir=%cd%"
C:\Users\K\Desktop>cd /d h:
H:\>echo doing somthing in %cd%
doing somthing in H:\
H:\>cd /D "%PopDir%"
C:\Users\K\Desktop>
Here is yet another way without Invoke-Expression but with two variables (command:string and parameters:array). It works fine for me. Assume 7z.exe is in the system path.
$cmd = '7z.exe'
$prm = 'a', '-tzip', 'c:\temp\with space\test1.zip', 'C:\TEMP\with space\changelog'
& $cmd $prm
If the command is known (7z.exe) and only parameters are variable then this will do
$prm = 'a', '-tzip', 'c:\temp\with space\test1.zip', 'C:\TEMP\with space\changelog'
& 7z.exe $prm
BTW, Invoke-Expression with one parameter works for me, too, e.g. this works
$cmd = '& 7z.exe a -tzip "c:\temp\with space\test2.zip" "C:\TEMP\with space\changelog"'
Invoke-Expression $cmd
P.S. I usually prefer the way with a parameter array because it is easier to compose programmatically than to build an expression for Invoke-Expression.
cmd.exeorpowershell.exe. I would recommend not starting environment variable names with a DOLLAR SIGN ($) character. Yes, it can work, but it might lead to confustion. Also,PATHis a well defined system variable that should generally not be redefined. Certainly not as anything other than the execution search path.cmd.exe, useSET "MY_VAR=value". Note the use and placement of QUOTATION MARK characters. However, for this question, it is better to use the value in aFORloop. Do not put a SPACE character before the EQUALS SIGN character. If it is done, the variableMY_VARwill be created. Note the SPACE character at the end of the variable name.