windows environment variables home directory 1

windows environment variables home directory

@echo off

set dirname=""
set dirname=%*
set orig_dirname=%*

:: remove quotes - will re-attach later.
set dirname=%dirname:\"=%
set dirname=%dirname:/"=%
set dirname=%dirname:"=%

:: restore dirnames that contained only "/"
if "%dirname%"=="" set dirname=%orig_dirname:"=%

:: strip trailing slash, if longer than 3
if defined dirname if NOT "%dirname:~3%"==""  (
    if "%dirname:~-1%"=="\" set dirname="%dirname:~0,-1%"
    if "%dirname:~-1%"=="/" set dirname="%dirname:~0,-1%"
)

set dirname=%dirname:"=%

:: if starts with ~, then replace ~ with userprofile path
if %dirname:~0,1%==~ (
    set dirname="%USERPROFILE%%dirname:~1%"
)
set dirname=%dirname:"=%

:: replace forward-slashes with back-slashes
set dirname="%dirname:/=\%"
set dirname=%dirname:"=%

chdir /D "%dirname%"

Here is what the above code is Doing:
1. It removes any quotes from the path.
2. It removes any trailing slashes from the path.
3. It replaces any ~ with the user’s profile path.
4. It replaces any forward slashes with back slashes.
5. It changes to the directory.

The code is a bit long, but it’s pretty simple. I’ve tested it on a few different paths, and it seems to work. I’m sure there are some edge cases that I haven’t thought of, but it should work for most paths.

Similar Posts