0
@echo off
set /p UserInput= What file would you like to hide?

cd %UserInput%

So I want to make a batch file that when run asks the user for a file, which it will hide in a maze of random folders. Let me explain.

Let's say I type C:\Program Files\Steam\butts.exe

It'd make a new directory in C:\Program Files\Steam

This is where I'm stuck. How do I have it find C:\Program Files\Steam from C:\Program Files\Steam\butts.exe?

Trinimon
  • 13,839
  • 9
  • 44
  • 60
ultimamax
  • 13
  • 3
  • semi-related: You should add `setlocal` to your script to encapsulate the variables. This will keep you from junking up your environment with a bunch of variables that ought to be limited to the scope of this one batch script. Also, if a user does `Ctrl`+`C` to break out of the script, having a `setlocal` will return the console back to the starting directory. See [this post](http://stackoverflow.com/a/15659309/1683264) for more information. – rojo Nov 18 '14 at 02:52
  • Also, you might be interested in using a [gui file chooser](http://stackoverflow.com/questions/15885132/) to capture the user's file choice. – rojo Nov 18 '14 at 03:00

3 Answers3

2

Hah! The quickest and hacksiest way would be just to add a \.. to the end. For instance, on my desktop I have a file called weather.xml. If I do this:

dir c:\users\me\Desktop\weather.xml\..

... I end up with a directory listing of my Desktop. :)

So you can accomplish what you need with

cd %UserInput%\..

Otherwise, you could pass the path to a for loop or call :label to a subroutine to end up with %%~dpX. See the last couple of pages of help for and help call for details.


If you want to be even hacksier, instead of requiring the user to enter the path\to\file to set %UserInput%, you can use powershell to launch a File... Open sort of file chooser. See this answer for details.

Community
  • 1
  • 1
rojo
  • 24,000
  • 5
  • 55
  • 101
2

Try this:

@echo off&setlocal 
for %%i in ("C:\Program Files\Steam\butts.exe") do set "steampath=%%~dpi"
:: remove last backslash
echo %steampath:~0,-1%
Endoro
  • 37,015
  • 8
  • 50
  • 63
1

You can use this batch

@echo off
set /p UserInput=What file would you like to hide?
for %%i in ("%UserInput%") do set path="%%~dpi"
cd %path%
Guido Preite
  • 14,905
  • 4
  • 36
  • 65
  • Using a `for` loop and `%%~dpI` is appropriate, but using "path" as the variable name is not a good idea. Add a `setlocal` below `@echo off` to avoid messing up the system `%PATH%` variable. Even if you choose to rename `path` to something else, `setlocal` is still good practice to keep from junking up your environment variables. – rojo Nov 18 '14 at 02:46