Ricardo Bessa
Ricardo Bessa

Reputation: 23

Need a little tip on batch files

I'm very new to coding and iI'm having a problem that is probably trivial, but is making me pull out my hair.

I'm using a batch script to automate mounting a VHD, executing a file inside and then pause until the user presses any key, which makes the VHD get unmounted and the script exits. This is the main batch file:

@echo off
set fileVHD=Gord

CD /D "%~dp0"

powershell -command "Start-Process mount.cmd '%~dp0%fileVHD%.vhd' -Verb runas" 
timeout /t 1

for /f %%D in ('wmic volume get DriveLetter^, Label ^| find "%fileVHD%"') do set usb=%%D

CD /D %usb%
index.html

echo "!!!!!!!!!!!!!!!!!!!!Press any key to fully close this program.!!!!!!!!!!!!!!!!!!!!!!!!!"
pause

CD /D "%~dp0"
powershell -command "Start-Process unmount.cmd '%~dp0%fileVHD%.vhd' -Verb runas"

exit

This is the mount script (Not made by me):

@echo off
setlocal enabledelayedexpansion

if "%~1"=="" (
    echo Usage: %~nx0 [vhd] [letter]
    exit /b 1
)
set "vhdPath=%~dpnx1"
set "driveLetter=%2"

if "!driveLetter!"=="" (
    echo Mounting "!vhdPath!"
) else (
    echo Mounting "!vhdPath!" to "!driveLetter!":
)

REM
REM create diskpart script
REM
set "diskPartScript=%~nx0.diskpart"
echo select vdisk file="!vhdPath!">"!diskPartScript!"
echo attach vdisk>>"!diskPartScript!"

REM assign the drive letter if requested
if not "!driveLetter!"=="" (
    echo select partition 1 >>"!diskPartScript!"
    echo assign letter="!driveLetter!">>"!diskPartScript!"
)

REM Show script
echo.
echo Running diskpart script:
type "!diskPartScript!"

REM
REM diskpart
REM
diskpart /s "!diskPartScript!"
del /q "!diskPartScript!"

echo Done!

endlocal

When all the files are located in a system path that contains no spaces, everything works fine. But it breaks where there are spaces. That means that somewhere in the code a path is badly defined by the lack of quotes, probably in the mount script. The trouble is that i don't fully grasp the mount script when it starts using all the "%~...." variable path names. I had to mix in some powershell commands because for some reason the script wouldn't work unless executed as Administrator.

If someone could give some insight to a newbie, it would be greatly appreciated.

Upvotes: 0

Views: 184

Answers (2)

Ricardo Bessa
Ricardo Bessa

Reputation: 23

Discovered the root of my problem. The path from script 1 was not being passed faithfully to script 2, even using using quotes or multiquotes.

Thanks for all the input guys!

Upvotes: 1

DSway
DSway

Reputation: 785

You need end quotes around your parameters when you change directory, i.e.

CD /D "%~dp0"

You can also see all of the %~ options by running 'help for' in a console window. In those scripts it's getting the path or filename from a variable.

Upvotes: 1

Related Questions