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.