0

I have been wanting my script to find a folder that starts with the string "onedrive...". My code looks like this,

@echo off

set path="C:\Users\%USERNAME%"

if exist %path% (
cd "%path%\onedrive*"
echo %cd%
cd
)
pause

and the output I get is,

C:\Users\310176421\Backupscript\source
C:\Users\310176421\OneDrive for Business

where the first one is my .bat file directory and the second one is the line i want to make into a variable.

Any ideas?

Pax Vobiscum
  • 2,551
  • 2
  • 21
  • 32

2 Answers2

1

Oh man don't do this, you are overwriting the system PATH. You have to use another name for that variable. And also you have to set it as local.

@echo off
SETLOCAL

REM blah blah
set _my_custom_path=....

ENDLOCAL
Paul
  • 2,620
  • 2
  • 17
  • 27
0

Here is a simple batch code which searches in profile directory of current user for a directory starting with string OneDrive and assigns the full path of first found folder without quotes to an environment variable output next before exiting batch.

@echo off
for /F "delims=" %%I in ('dir /AD /B /S "%USERPROFILE%\OneDrive*" 2^>nul') do (
    set "OneDriveFolder=%%~I"
    goto FoundFolder
)
echo Could not find a folder OneDrive.
goto :EOF

:FoundFolder
echo Found folder: %OneDriveFolder%
set "OneDriveFolder="

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

  • dir /?
  • for /?
  • goto /?
  • set /?

Note 1: C:\Users\%USERNAME% is not always equal %USERPROFILE% as the profile directory can be also on another drive than drive C: and Users is just the default parent directory for the user profiles on Windows Vista and later.

Note 2: 2^>nul redirects error message output by command DIR to stdout to device nul which means suppressing the error message in case of no directory starting with OneDrive is found case-insensitive. ^ escapes redirection operator > for command FOR to get 2>nul applied on command DIR.

Mofi
  • 46,139
  • 17
  • 80
  • 143