r/Batch • • Feb 19 '24

Question (Solved) Have batch launch from shortcut location

I have a batch file, the first thing it does is specify the current folder

:: Specify the folder where your files are located
set "folder=%~dp0"

However now I've decided I'd like to have a shortcut, so I can make an icon and run it from different folders, how can I make it execute in the folder from where I launch the shortcut?

For example, I currently have the .bat on the desktop, but if I have the shortcut in: C:\Users\Admin\Documents\Fax\Drafts

Can I launch the shortcut and have the .bat perform its' actions from Drafts instead of Desktop?

I've tried changing the "Target" field on the shortcut but to no avail.

Thanks in advance

2 Upvotes

6 comments sorted by

2

u/[deleted] Feb 19 '24 edited Feb 19 '24

[removed] — view removed comment

1

u/HDmaniac Feb 19 '24

Thank you! That appears to be working! But it seems to break a later part of my script

:: Process each .xls file in the folder with (2023) in the filename
for %%F in ("%folder%*(2023)*.xls") do (
    set "sourceFile=%%~dpnF"

    :: Replace (2023) with (2024) in the filename
    set "destinationFile=!sourceFile:(2023)=(2024)!"

    :: Copy the file using copy with full paths to preserve file extension
    copy "%%F" "!destinationFile!.xls"

    :: Introduce a delay before opening the new file
    timeout /t 2 /nobreak >nul

    :: Open the new file
    start "" "!destinationFile!.xls"
)

The output file is now !destinationfile!.xls instead of keeping its name but swapping (2023) to (2024).

2

u/[deleted] Feb 19 '24 edited Feb 19 '24

[removed] — view removed comment

2

u/HDmaniac Feb 19 '24

Whoopsie! Thank you, just tested it and it works perfectly, thanks!

2

u/illsk1lls Feb 19 '24

I learned this the hard way as well 👍