Home > Software engineering >  save PowerShell command in variable and execute in cmd
save PowerShell command in variable and execute in cmd

Time:09-26

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"

CodePudding user response:

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

CodePudding user response:

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.

  • Related