The Iszi answer will often appear to work, but it can give the wrong result under many circumstances.
The FINDSTR search could fail to match properly if there is a difference in case. Solved by using the /I
option.
FINDSTR will treat search string as two or more search strings if the profile name includes a space. Better to use the /C:"searchString"
option.
FINDSTR will do a regex search if %USERPROFILE%
includes a regex meta-character like .
. This can be solved by forcing a literal search using either the /L
option, or the /C:"searchString"
option.
Backslashes can be a bit tricky with FINDSTR, since it is used by FINDSTR as an escape character. Safer to escape all backslashes as \\
.
The ECHO command can fail if the current directory name contains a special character like &
. The CD
command will safely print the current directory without having to worry about special characters.
Also, since FINDSTR is being used as a test, and there is no interest in seeing the matching line, then the output should be redirected to NUL.
And finally, the solution can be simplified by replacing the IF statement with the conditional &&
and ||
operators.
The following code should always work:
cd|findstr /bic:"%userprofile:\=\\%" >nul&&echo You can do stuff here!||echo You don't belong here!
Update - Example of varying drive letter case
Here is a Windows 7 cmd.exe session that demonstrates how the case of the drive letter reported by CD
(or %CD%
) can vary:
Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation. All rights reserved.
C:\>set userprofile
USERPROFILE=C:\Users\Dave
C:\>cd c:\users\Dave
c:\Users\Dave>cd
c:\Users\Dave
c:\Users\Dave>echo CD=%CD%
CD=c:\Users\Dave
c:\Users\Dave>cd..
c:\Users>cd C:\users\Dave
C:\Users\Dave>cd
C:\Users\Dave
C:\Users\Dave>echo CD=%CD%
CD=C:\Users\Dave
C:\Users\Dave>