Suppress error messages in Windows commandline - windows

Let's say I already have a folder created on the next path file: "C:\users\charqus\desktop\MyFolder", and I run the next command on CMD:
mkdir "C:\users\charqus\desktop\MyFolder"
I get a message like this: "A subdirectory or file C:\users\charqus\desktop\MyFolder already exists".
Therefore, is there any command in the commandline to get rid of this returned messages?
I tried echo off but this is not what I looking for.

Redirect the output to nul
mkdir "C:\users\charqus\desktop\MyFolder" > nul
Depending on the command, you may also need to redirect errors too:
mkdir "C:\users\charqus\desktop\MyFolder" > nul 2> nul
Microsoft describes the options here, which is useful reading.

A previous answer shows how to squelch all the output from the command. This removes the helpful error text that is displayed if the command fails. A better way is shown in the following example:
C:\test>dir
Volume in drive C has no label.
Volume Serial Number is 4E99-B781
Directory of C:\test
20/08/2015 20:18 <DIR> .
20/08/2015 20:18 <DIR> ..
0 File(s) 0 bytes
2 Dir(s) 214,655,188,992 bytes free
C:\test>dir new_dir >nul 2>nul || mkdir new_dir >nul 2>nul || mkdir new_dir
C:\test>dir new_dir >nul 2>nul || mkdir new_dir >nul 2>nul || mkdir new_dir
As is demonstrated above this command successfully suppress the original warning. However, if the directory can not be created, as in the following example:
C:\test>icacls c:\test /deny "Authenticated Users":(GA)
processed file: c:\test
Successfully processed 1 files; Failed processing 0 files
C:\test>dir new_dir2 >nul 2>nul || mkdir new_dir2 >nul 2>nul || mkdir new_dir2
Access is denied.
Then as can be seen, an error message is displayed describing the problem.

Related

Exist, Rmdir and %errorlevel% in batch Windows [duplicate]

I'm writing a batch (.bat) script and I need to handle the case in which the deletion of a folder fails. I'm using %errorlevel% to catch the exit code, but in the case of the rd command it seems not to work:
C:\Users\edo\Desktop>rd testdir
Directory is not empty
C:\Users\edo\Desktop>echo %errorlevel%
0
Why? What do you suggest?
Wow, this is the 2nd case I've seen where ERRORLEVEL is not set properly! See File redirection in Windows and %errorlevel%.
The solution is the same as for detecting redirection failure. Use the || operator to take action upon failure.
rd testdir || echo The command failed!
The bizarre thing is, when you use the || operator, the ERRORLEVEL is then set properly to 145 if the folder was not empty, or 2 if the folder did not exist. So you don't even need to do anything. You could conditionally "execute" a remark, and the errorlevel will then be set properly.
rd testdir || rem
echo %errorlevel%
I thought the above gave a complete picture. But then a series of comments below demonstrated there are still potential problems when /RD /S is used.
If a file or subfolder under the parent folder is locked (at any level under parent) then RD /S /Q PARENT && echo removed || echo failed will print out an error message, but the && branch fires instead of the || branch. Very unfortunate. If the command fails because the parent folder itself is locked, then || will properly fire and set the ERRORLEVEL.
It is possible to detect failure in all cases by swapping stderr with stdout and piping the result to FINDSTR "^". If a match is found, then there must have been an error.
3>&2 2>&1 1>&3 rd /s test | findstr "^" && echo FAILED
The swap of stderr and stdout is important when /q is missing because it allows the "Are you sure (Y/N)?" prompt to be visible on stderr, separate from the error message on stdout.
rd does not set errorlevel to zero - it leaves errorlevel intact: f.e. if previous operation ends in positive errorlevel and rd finishes successfully it leaves errorlevel unchanged. Example: error levels of robocopy below 4 are warnings and not errors and can be ignored so the following code may end with error even when the directory was deleted successfully:
robocopy ...
if errorlevel 4 goto :error
rd somedir
if errorlevel 1 goto :error
Solution: ignore the error and check if the directory still exists after rd:
rd somedir
if exist somedir goto :error

Can't stack robocopy and ren in batch

I am trying to carry out three commands in batch at once in Windows: robocopy, cd and ren. An example is that I'd like to copy files to another directory and then add .bak after their names. I use && to stack the commands:
robocopy C:\original D:\backup && cd D:\backup && ren * *.bkp
However, it seems like if I just type in this first bit to the command prompt:
robocopy C:\original D:\backup && cd D:\backup
the directory doesn't actually change. I need to insert the second command manually.
I also tried
robocopy C:\original D:\backup && ren D:\backup\* *.bkp
Again, it only works if I manually carry out the commands separately. If I carry out the whole command, only the first bit (robocopy) is carried out.
&& means to performs the next command only if the previous command was successful (or returned an errorlevel of 0). Similarly, || only performs the next command if the previous command failed (or returns an errorlevel greater than 0)
Some examples would be:
copy null null || echo this command failed
rundll32 && echo this command was successful
copy 1.txt 2.txt && echo success || echo failed
So if you wanted to copy a file, change directory and then rename a file, you would do something similar to:
robocopy C:\original D:\backup & cd D:\backup & ren * *.bkp
Bear in mind that if robocopy fails to copy just 1 file (or more) then you can't use &&
A more robust option would check if D:\backup exists:
(robocopy C:\original D:\backup & if exist "D:\backup" (pushd D:\backup & ren * *.bkp) else (echo Failed to create D:\backup 2>nul)) >nul
It will pushd into the directory, and only if the robocopy command was successful would it rename the files, additionally hiding all messages except errors

Renaming a file using batch running in a wrapper batch

I'm trying to run a simple rename command for renaming an ".html" file to ".htm" file as a batch file. Following is my command:
ren index.html index.htm
This seems to be running fine as a part of CopyFiles.bat. The problem comes when I try to run this as a part of a batch wrapper WrapAll.bat. The file is renamed but the following error is logged:
The system cannot find the path specified.
Can someone please help in understanding why am I getting this error when trying to run the CopyFiles.bat within WrapAll.bat. This is impacting the subsequent commands as I'm checking for %errorlevel% to be 0 and i get %errorlevel% as 1 from this command.
Edit:
Directory Structure:
This is the directory structure for the files. CopyFiles.bat/WrapAll.bat are in Coverage\Scripts and index.html is in Coverage\Code\Coverage_2
CopyFiles.bat:
cd %~dp0
call :DoThis
cd "%~dp0..\Code\Coverage_2"
if exist "index.htm" del "index.htm" /f /s /q
ren index.html index.htm
cd "%~dp0..\Code"
if %errorlevel% equ 0 (
ECHO "Do Something here"
)
exit /b %errorlevel%
:DoThis
ECHO "Doing this"
exit /b %errorlevel%
WrapAll.bat:
set logPath="%~dp0ErrorLog_%DATE:~-4%-%DATE:~4,2%-%DATE:~7,2%.log"
cd %~dp0
call "CopyFiles.bat" 2>>%logPath%
After 2 hours of re-running the script, I finally found the issue, its not the rename but the cd command after that causing the problem.
cd "%~dp0..\Code"
should be
cd "%~dp0.."

BATCH- How to put a variable into the move command?

Okay, this is my first question on Stackoverflow, so I'll try to make it a good one.
I've searched all over the web and I couldn't find any information to this. I have created a little batch file that prompts you to put in the name of a file that you would like to move. After that, it asks your your usersname. The problem I'm having is cmd tells me I have incorrect syntax.
Can anyone see what I did wrong?
Below is the code I am using. I just pasted in the part that is having trouble.
Thanks guys!
echo Place the file you wish to move to the Windows Startup Folder on your desktop.
echo When you have placed it there, type in the name of your file, NOT INCLUDING the extension.
echo Example: The file's name is: myfile.bat You type in: myfile
set/p "filename=>"
echo %filename%
echo Next, type in your username.
echo Example: acly6
set/p "USERNAME=>"
echo %USERNAME%
ping 192.2.0.0 -n 1 -w 500 > nul
goto MOVE
:MOVE
echo Moving your file to your startup folder.
move C:\Users\%USERNAME%\Desktop\%filename%.bat
C:\Users\%USERNAME%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\
ping 192.2.0.0 -n 1 -w 1000 > nul
echo Checking Volumes...
ping 192.2.0.0 -n 1 -w 3000 > nul
if EXIST C:\Users\%USERNAME%\AppData\Roaming\Microsoft\Windows\StartMenu\Programs\Startup\%filename%goto COMPLETED
goto FAILED
I editted a bit your script:
Surrounded filepaths with double quotes
Added /y parameter to move command to override automatically the file in new location (if exists)
Spotted some issues:
goto MOVE
:MOVE has no sense as it will continue anyway that path.
goto FAILED GOTO COMPLETED - there're no such labels in your script.
Please shout if you have other problems.
#echo off
echo Place the file you wish to move to the Windows Startup Folder on your desktop.
echo When you have placed it there, type in the name of your file, NOT INCLUDING the extension.
echo Example: The file's name is: myfile.bat You type in: myfile
set/p "filename=>"
echo %filename% echo Next, type in your username.
echo Example: acly6
set/p "USERNAME=>"
echo %USERNAME%
ping 192.2.0.0 -n 1 -w 500 > nul
goto MOVE
:MOVE
echo Moving your file to your startup folder.
move /Y "C:\Users\%USERNAME%\Desktop\%filename%.bat" "C:\Users\%USERNAME%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\"
ping 192.2.0.0 -n 1 -w 1000 > nul
echo Checking Volumes...
ping 192.2.0.0 -n 1 -w 3000 > nul
if EXIST "C:\Users\%USERNAME%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\%filename%" goto COMPLETED
goto FAILED
:FAILED

How to test if a file is a directory in a batch script?

Is there any way to find out if a file is a directory?
I have the file name in a variable. In Perl I can do this:
if(-d $var) { print "it's a directory\n" }
This works:
if exist %1\* echo Directory
Works with directory names that contains spaces:
C:\>if exist "c:\Program Files\*" echo Directory
Directory
Note that the quotes are necessary if the directory contains spaces:
C:\>if exist c:\Program Files\* echo Directory
Can also be expressed as:
C:\>SET D="C:\Program Files"
C:\>if exist %D%\* echo Directory
Directory
This is safe to try at home, kids!
Recently failed with different approaches from the above. Quite sure they worked in the past, maybe related to dfs here. Now using the files attributes and cut first char
#echo off
SETLOCAL ENABLEEXTENSIONS
set ATTR=%~a1
set DIRATTR=%ATTR:~0,1%
if /I "%DIRATTR%"=="d" echo %1 is a folder
:EOF
You can do it like so:
IF EXIST %VAR%\NUL ECHO It's a directory
However, this only works for directories without spaces in their names. When you add quotes round the variable to handle the spaces it will stop working. To handle directories with spaces, convert the filename to short 8.3 format as follows:
FOR %%i IN (%VAR%) DO IF EXIST %%~si\NUL ECHO It's a directory
The %%~si converts %%i to an 8.3 filename. To see all the other tricks you can perform with FOR variables enter HELP FOR at a command prompt.
(Note - the example given above is in the format to work in a batch file. To get it work on the command line, replace the %% with % in both places.)
Further to my previous offering, I find this also works:
if exist %1\ echo Directory
No quotes around %1 are needed because the caller will supply them.
This saves one entire keystroke over my answer of a year ago ;-)
Here's a script that uses FOR to build a fully qualified path, and then pushd to test whether the path is a directory. Notice how it works for paths with spaces, as well as network paths.
#echo off
if [%1]==[] goto usage
for /f "delims=" %%i in ("%~1") do set MYPATH="%%~fi"
pushd %MYPATH% 2>nul
if errorlevel 1 goto notdir
goto isdir
:notdir
echo not a directory
goto exit
:isdir
popd
echo is a directory
goto exit
:usage
echo Usage: %0 DIRECTORY_TO_TEST
:exit
Sample output with the above saved as "isdir.bat":
C:\>isdir c:\Windows\system32
is a directory
C:\>isdir c:\Windows\system32\wow32.dll
not a directory
C:\>isdir c:\notadir
not a directory
C:\>isdir "C:\Documents and Settings"
is a directory
C:\>isdir \
is a directory
C:\>isdir \\ninja\SharedDocs\cpu-z
is a directory
C:\>isdir \\ninja\SharedDocs\cpu-z\cpuz.ini
not a directory
This works perfectly
if exist "%~1\" echo Directory
we need to use %~1 to remove quotes from %1, and add a backslash at end. Then put thw whole into qutes again.
CD returns an EXIT_FAILURE when the specified directory does not exist. And you got conditional processing symbols, so you could do like the below for this.
SET cd_backup=%cd%
(CD "%~1" && CD %cd_backup%) || GOTO Error
:Error
CD %cd_backup%
A variation of #batchman61's approach (checking the Directory attribute).
This time I use an external 'find' command.
(Oh, and note the && trick. This is to avoid the long boring IF ERRORLEVEL syntax.)
#ECHO OFF
SETLOCAL EnableExtensions
ECHO.%~a1 | find "d" >NUL 2>NUL && (
ECHO %1 is a directory
)
Outputs yes on:
Directories.
Directory symbolic links or junctions.
Broken directory symbolic links or junctions. (Doesn't try to resolve links.)
Directories which you have no read permission on (e.g. "C:\System Volume Information")
The NUL technique seems to only work on 8.3 compliant file names.
(In other words, `D:\Documents and Settings` is "bad" and `D:\DOCUME~1` is "good")
I think there is some difficulty using the "NUL" tecnique when there are SPACES in the directory name, such as "Documents and Settings."
I am using Windows XP service pack 2 and launching the cmd prompt from %SystemRoot%\system32\cmd.exe
Here are some examples of what DID NOT work and what DOES WORK for me:
(These are all demonstrations done "live" at an interactive prompt. I figure that you should get things to work there before trying to debug them in a script.)
This DID NOT work:
D:\Documents and Settings>if exist "D:\Documents and Settings\NUL" echo yes
This DID NOT work:
D:\Documents and Settings>if exist D:\Documents and Settings\NUL echo yes
This DOES work (for me):
D:\Documents and Settings>cd ..
D:\>REM get the short 8.3 name for the file
D:\>dir /x
Volume in drive D has no label.
Volume Serial Number is 34BE-F9C9
Directory of D:\
09/25/2008 05:09 PM <DIR> 2008
09/25/2008 05:14 PM <DIR> 200809~1.25 2008.09.25
09/23/2008 03:44 PM <DIR> BOOST_~3 boost_repo_working_copy
09/02/2008 02:13 PM 486,128 CHROME~1.EXE ChromeSetup.exe
02/14/2008 12:32 PM <DIR> cygwin
[[Look right here !!!! ]]
09/25/2008 08:34 AM <DIR> DOCUME~1 Documents and Settings
09/11/2008 01:57 PM 0 EMPTY_~1.TXT empty_testcopy_file.txt
01/21/2008 06:58 PM <DIR> NATION~1 National Instruments Downloads
10/12/2007 11:25 AM <DIR> NVIDIA
05/13/2008 09:42 AM <DIR> Office10
09/19/2008 11:08 AM <DIR> PROGRA~1 Program Files
12/02/1999 02:54 PM 24,576 setx.exe
09/15/2008 11:19 AM <DIR> TEMP
02/14/2008 12:26 PM <DIR> tmp
01/21/2008 07:05 PM <DIR> VXIPNP
09/23/2008 12:15 PM <DIR> WINDOWS
02/21/2008 03:49 PM <DIR> wx28
02/29/2008 01:47 PM <DIR> WXWIDG~2 wxWidgets
3 File(s) 510,704 bytes
20 Dir(s) 238,250,901,504 bytes free
D:\>REM now use the \NUL test with the 8.3 name
D:\>if exist d:\docume~1\NUL echo yes
yes
This works, but it's sort of silly, because the dot already implies i am in a directory:
D:\Documents and Settings>if exist .\NUL echo yes
I use this:
if not [%1] == [] (
pushd %~dpn1 2> nul
if errorlevel == 1 pushd %~dp1
)
This works and also handles paths with spaces in them:
dir "%DIR%" > NUL 2>&1
if not errorlevel 1 (
echo Directory exists.
) else (
echo Directory does not exist.
)
Probably not the most efficient but easier to read than the other solutions in my opinion.
A very simple way is to check if the child exists.
If a child does not have any child, the exist command will return false.
IF EXIST %1\. (
echo %1 is a folder
) else (
echo %1 is a file
)
You may have some false negative if you don't have sufficient access right (I have not tested it).
If you can cd into it, it's a directory:
set cwd=%cd%
cd /D "%1" 2> nul
#IF %errorlevel%==0 GOTO end
cd /D "%~dp1"
#echo This is a file.
#goto end2
:end
#echo This is a directory
:end2
#REM restore prior directory
#cd %cwd%
Based on this article titled "How can a batch file test existence of a directory" it's "not entirely reliable".
BUT I just tested this:
#echo off
IF EXIST %1\NUL goto print
ECHO not dir
pause
exit
:print
ECHO It's a directory
pause
and it seems to work
Here's my solution:
REM make sure ERRORLEVEL is 0
TYPE NUL
REM try to PUSHD into the path (store current dir and switch to another one)
PUSHD "insert path here..." >NUL 2>&1
REM if ERRORLEVEL is still 0, it's most definitely a directory
IF %ERRORLEVEL% EQU 0 command...
REM if needed/wanted, go back to previous directory
POPD
I would like to post my own function script about this subject hope to be useful for someone one day.
#pushd %~dp1
#if not exist "%~nx1" (
popd
exit /b 0
) else (
if exist "%~nx1\*" (
popd
exit /b 1
) else (
popd
exit /b 3
)
)
This batch script checks if file/folder is exist and if it is a file or a folder.
Usage:
script.bat "PATH"
Exit code(s):
0: file/folder doesn't exist.
1: exists, and it is a folder.
3: exists, and it is a file.
Under Windows 7 and XP, I can't get it to tell files vs. dirs on mapped drives. The following script:
#echo off
if exist c:\temp\data.csv echo data.csv is a file
if exist c:\temp\data.csv\ echo data.csv is a directory
if exist c:\temp\data.csv\nul echo data.csv is a directory
if exist k:\temp\nonexistent.txt echo nonexistent.txt is a file
if exist k:\temp\something.txt echo something.txt is a file
if exist k:\temp\something.txt\ echo something.txt is a directory
if exist k:\temp\something.txt\nul echo something.txt is a directory
produces:
data.csv is a file
something.txt is a file
something.txt is a directory
something.txt is a directory
So beware if your script might be fed a mapped or UNC path. The pushd solution below seems to be the most foolproof.
This is the code that I use in my BATCH files
```
#echo off
set param=%~1
set tempfile=__temp__.txt
dir /b/ad > %tempfile%
set isfolder=false
for /f "delims=" %%i in (temp.txt) do if /i "%%i"=="%param%" set isfolder=true
del %tempfile%
echo %isfolder%
if %isfolder%==true echo %param% is a directory
```
Here is my solution after many tests with if exist, pushd, dir /AD, etc...
#echo off
cd /d C:\
for /f "delims=" %%I in ('dir /a /ogn /b') do (
call :isdir "%%I"
if errorlevel 1 (echo F: %%~fI) else echo D: %%~fI
)
cmd/k
:isdir
echo.%~a1 | findstr /b "d" >nul
exit /b %errorlevel%
:: Errorlevel
:: 0 = folder
:: 1 = file or item not found
It works with files that have no extension
It works with folders named folder.ext
It works with UNC path
It works with double-quoted full path or with just the dirname or filename only.
It works even if you don't have read permissions
It works with Directory Links (Junctions).
It works with files whose path contains a Directory Link.
One issue with using %%~si\NUL method is that there is the chance that it guesses wrong. Its possible to have a filename shorten to the wrong file. I don't think %%~si resolves the 8.3 filename, but guesses it, but using string manipulation to shorten the filepath. I believe if you have similar file paths it may not work.
An alternative method:
dir /AD %F% 2>&1 | findstr /C:"Not Found">NUL:&&(goto IsFile)||(goto IsDir)
:IsFile
echo %F% is a file
goto done
:IsDir
echo %F% is a directory
goto done
:done
You can replace (goto IsFile)||(goto IsDir) with other batch commands:
(echo Is a File)||(echo is a Directory)
If your objective is to only process directories then this will be useful.
This is taken from the https://ss64.com/nt/for_d.html
Example... List every subfolder, below the folder C:\Work\ that has a name starting with "User":
CD \Work
FOR /D /r %%G in ("User*") DO Echo We found
FOR /D or FOR /D /R
#echo off
cd /d "C:\your directory here"
for /d /r %%A in ("*") do echo We found a folder: %%~nxA
pause
Remove /r to only go one folder deep. The /r switch is recursive and undocumented in the command below.
The for /d help taken from command for /?
FOR /D %variable IN (set) DO command [command-parameters]
If set contains wildcards, then specifies to match against directory
names instead of file names.
I was looking for this recently as well, and had stumbled upon a solution which has worked for me, but I do not know of any limitations it has (as I have yet to discover them). I believe this answer is similar in nature to TechGuy's answer above, but I want to add another level of viability. Either way, I have had great success expanding the argument into a full fledged file path, and I believe you have to use setlocal enableextensions for this to work properly.
Using below I can tell if a file is a directory, or opposite. A lot of this depends on what the user is actually needing. If you prefer to work with a construct searching for errorlevel vs && and || in your work you can of course do so. Sometimes an if construct for errorlevel can give you a little more flexibility since you do not have to use a GOTO command which can sometimes break your environment conditions.
#Echo Off
setlocal enableextensions
Dir /b /a:D "%~f1" && Echo Arg1 is a Folder || Echo Arg1 is NOT a Folder
Dir /b /a:-D "%~f1" && Echo Arg1 is a File || Echo Arg1 is NOT a File
pause
Using this you could simply drag and drop your file(s) onto the tool you are building to parse them out. Conversely, if you are using other means to comb your file structure and you already have the file and are not dragging/dropping them onto the batch file, you could implement this:
#Echo Off
setlocal enableextensions
Dir /b /s "C:\SomeFolderIAmCombing\*" >"%~dp0SomeFiletogoThroughlater.txt"
For /f "Usebackq Delims=" %%a in ("%~dp0SomeFiletogoThroughlater.txt") do (
Call:DetectDir "%%a"
)
REM Do some stuff after parsing through Files/Directories if needed.
REM GOTO:EOF below is used to skip all the subroutines below.
REM Using ' CALL:DetectDir "%%a" ' with the for loop keeps the for
REM loop environment running in the background while still parsing the given file
REM in a clean environment where GOTO and other commmands do not need Variable Expansion.
GOTO:EOF
:DetectDir [File or Folder being checked]
REM Checks if Arg1 is a Directory. If yes, go to Dir coding. If not, go to File coding.
Dir /b /a:D "%~f1" && Echo Arg1 is a Folder & GOTO:IsDir || Echo Arg1 is NOT a Folder & GOTO:IsFile
REM Checks if Arg1 is NOT a Directory. If Yes, go to File coding. If not, go to Dir coding
Dir /b /a:-D "%~f1" && Echo Arg1 is a File & GOTO:IsFile || Echo Arg1 is NOT a File & GOTO:IsDir
:IsDir
REM Do your stuff to the Folder
GOTO:EOF
:IsFile
REM do your stuff to the File
GOTO:EOF
Can't we just test with this :
IF [%~x1] == [] ECHO Directory
It seems to work for me.

Resources