get current folder only using %~p0

Microsoft Windows
Post Reply
User avatar
MigrationUser
Posts: 336
Joined: 2021-Jul-12, 1:37 pm
Contact:

get current folder only using %~p0

Post by MigrationUser »

09 Jul 2015 01:47
NDog

Hi there

I am looking for some help with getting the parent folder of myscript.cmd only (not full path)
I would like to do this avoiding third party util, however if not possible I will use .vbs instead

Please note that the below does not work, since I am executing this script from the working system32 folder, so %~p0 must be used

Code: Select all

for %%a in (.) do set _currentfolder=%%~na

What I am thinking is to do a for loop as such, using \ as a deliminator, and using SHIFT, however I do not have exeperience with SHIFT command.

Code: Select all

for %%s in (%dp0) do cd %%~ps 
eg - 1\2\3\4\5\6\7\8\9\really long path\abcdefghijklmnopqrstuvwxyz\foo!OS!bar%PROMPT%baz\Technical Experts Exchange ss64 rocks\RD 123\VPN 456\parent folder\myscript.cmd

and shift \parent folder\ to the start and get that value

the problem is that foo!OS!bar%PROMPT%baz could be considered a valid path, and or I might have a really long path

Any takers?

cmd, vbs, ps, bash
autoit, python, swift

----------------------------

#2 09 Jul 2015 05:06
RG


Try one of these :
http://stackoverflow.com/questions/3003 ... and-prompt

Windows Shell Scripting and InstallShield

----------------------------

#3 09 Jul 2015 05:47
NDog

Thanks RG

I shamelessly stole the code and modified as I needed. Not the most eloquint solution to get the parent path but it suits my needs.

Interesting how the for loop uses the final value it processes, and preserves spaces, quite clever.

Code: Select all

@echo off&title %~n0

call set PARENT_DIR=%~p0
set PARENT_DIR=%PARENT_DIR: =/%
set PARENT_DIR=%PARENT_DIR:\= %
set LAST_DIR=
for %%i in (%PARENT_DIR%) do set LAST_DIR=%%i
set _parentdir=%LAST_DIR:/= %

set _vpnname=%_parentdir% VPN
etc

cmd, vbs, ps, bash
autoit, python, swift

----------------------------

#4 10 Jul 2015 04:34
foxidrive


This will give you the holding and parent folder names.

Code: Select all

@echo off
for %%a in ("%~dp0\.") do echo "%%~nxa"

for %%a in ("%~dp0\.") do for %%b in ("%%~dpa\.") do echo "%%~nxb"

pause
Last edited by foxidrive (10 Jul 2015 04:36)

----------------------------

#5 11 Jul 2015 21:09
bluesxman


foxidrive - nice misuse of "for"

cmd | *sh | ruby | chef

----------------------------

#6 12 Jul 2015 07:07
foxidrive
bluesxman wrote:

foxidrive - nice misuse of "for"
Ta. Here's me misusing a saying :)

It's all fair game in love and batch files.

Last edited by foxidrive (12 Jul 2015 07:07)

----------------------------

#7 31 Jul 2015 06:55
NDog


:D Thank you foxidrive! perfect

Code: Select all

@echo off&title %~n0
for %%a in ("%~dp0\.") do set _parentdir=%%~nxa
cmd, vbs, ps, bash
autoit, python, swift
Post Reply