Reputation: 61
I have a bat file that extracts the target of the given shortcut in the parameter
@echo off
set "paf=%*"
for /f "delims=" %%a in ('wmic path win32_shortcutfile where "name='%paf:\=\\%'" get target /value') do (
for /f "tokens=2 delims==" %%b in ("%%~a") do CALL SET shortcutPath=%%a
)
The return is like: C:\Users\MyUser\Desktop\SomeFolder\target.exe
All I want is to get the folder path without the executable name. This is a bat that I'll use constantly with different given shortcuts from many locations so it has to be relative.
On how to achieve this, I thought on exclude all characters from the last delimiter found, the delimiter should be \ and it will exclude anything on the right side of the last one found. The thing is I have no idea how to do that, or even if this is possible
Can someone bring some help on this? Thank you
Upvotes: 1
Views: 84
Reputation: 30113
Instead of CALL SET shortcutPath=%%a
, use
SET "shortcutPath=%%~dpb"
The result should be C:\Users\MyUser\Desktop\SomeFolder\
in your given example.
For explanation, read and follow for /?
:
%~dpI - expands %I to a drive letter and path only
Read more about using quotes in https://ss64.com/nt/set.html.
Upvotes: 0
Reputation: 38623
The simplest way is to use the already existing output Target
name, instead of assigning the name shortcutPath
to it. As long as your passed argument is a valid and working shortcut file, your resulting variable will be accessible as %Target%
.
Set "Target=" & For /F "Delims=" %%G In ('%SystemRoot%\System32\wbem\WMIC.exe
Path Win32_ShortcutFile Where "Name='%Lnk:\=\\%'" Get Target /Value 2^>NUL'
) Do For /F "Delims=" %%H In ("%%G") Do Set "%%H"
Then given your Target
variable contains the full path and file name, you can use variable expansion modifiers to return its drive and path only:
If Defined Target For %%G In ("%Target%") Do Echo %%~dpG
If you want it without the trailing backwards slash, you could return that by including another for
loop, and changing the modifier:
For %%G In ("%Target%") Do For %%H In ("%%~dpG.") Do Echo %%~fH
Upvotes: 1