How place file with bat command when ran from currenty directory - windows

So I am trying to create a bat/exe installer for regjump. I am using a bat compiler so I can attach the "regjump.exe" to the installer.exe; so when the installer is ran, it will put regjump in the current directory of the installer.exe. I know I can use xcopy to place the file but I need help with the first half of the command. What is "local directory\regjump.exe" syntax?
cd C:\
xcopy "WHEREVER THE INSTALLER IS RAN FROM\regjump.exe" "C:\Windows\System32" /q /y /r
I want the syntax to be able to be ran from anywhere i.e. removable F:

Try this. You will need to execute as admin to write to "C:\Windows\System32", so this checks for that.
openfiles >nul 2>&1 || echo(You must execute this command as Administrator. & pause & goto :eof
set "SourceDir=%CD%
cd C:\
xcopy "%SourceDir%\regjump.exe" "C:\Windows\System32" /q /y /r

Related

How do I make a batch file delete it's own directory?

Okay, I apologize that I am very new at this, but I am trying to make my batch file delete it's own directory after it has been launched. This is how my folders are arranged:
Folder1
delete.bat
My goal is to make "delete.bat" delete "Folder1" after "delete.bat" has been launched. So here's my code:
rd /s /q %~dp0..\Folder1
This seems like it would work but it only deletes the contents of "Folder1" rather than the whole directory itself. What am I doing wrong?
Some thoughts...
%~dp0 gets the drive and path of the batch file, so you don't need to include ..\Folder1.
What you have should work. If it's not removing the folder itself, it means that it's locked, probably because cmd's current folder is Folder1. (That's a likely guess, but it's not the only reason it might be locked.) If it is cmd, you'll have to call the batch file from another folder, outside of Folder1.
While what you have will work, it will result in a funny error when resuming the non-existent batch file: The system cannot find the path specified. You can avoid that in the solution below.
One good solution: start /b "" cmd /c rd /s /q "%~dp0"
This creates a new process to remove the folder (and everything in it, including the batch file itself). Be careful. =)
From the corresponding MSDN link for rd:
You cannot use rmdir to delete the current directory. You must first change to a different directory (not a subdirectory of the current directory) and then use rmdir with a path.
I guess this is what's going wrong in your case since the batch file is located within the directory that you're trying to delete.
My implementation is effectively the same as Soja's, plus the info from dbenham's comment. I have added a 2-sec delay, to ensure there are no timing issues, even though I believe the error when the .bat file is deleting itself is harmless.
#echo off
:: Do the work
...your command here...
:: In order to delete the current dir we are running from (and all subdirs), none of them can be the
:: current working directory of any running process. Therefore, we are setting our own CWD to something
:: else, so it will be inherited by the below cmd.exe.
cd /d %temp%
:: The countdown is there to allow this batch file to exit, so it can then be deleted safely.
set DelayedSelfDeleteCommand="timeout /t 2 >NUL && rmdir /s /q "%~dp0""
:: Start a separate process (without waiting for it), to execute the command
start "" /b cmd.exe /C %DelayedSelfDeleteCommand%
Well I think it cannot be done (at least as normal user)
start /b "" cmd /c rd /s "%~dp0"
deletes folder but only with right permissions I think
start /b "" cmd /c rmdir /s "C:/folder"
This has the same result
del /s /q "C:\Temp\folder\*"
rmdir /s /q "C:\Temp\folder"
del %0
only way as for batch files is to use vbs script or autohotkey (send !{Space} // send e // send p formula) or hack it, you can delete only file used and content of folder but not working directory due to specification of cmd. Any other language would have no problem with it cuz it in RAM memory.
I recommend this way to do it (as for normal users):
in your bat file add
copy C:\urpath\deleteafter.bat C:\Temp\deleteafter.bat
start "" autohotkey.exe "X:\patchto\deletebatchfile.ahk"
deletebatchfile.ahk
sleep 2000
Run, C:\Temp\deleteafter.bat, C:\Temp\
deleteafter.bat
rmdir /s /q "C:\Temp\batfileworkingpath"
sleep 3
del %0

copying all the elements of a folder into another folder using a loop in batch file

I want to copy all the files of a folder into some other folders using batch script. Say, I have two folders named folder1 and folder2. these two folders are located in C:\Users\xyz . I want to copy the elements of another folder (say, folder3 which is located in C:\Users\abc\def) into these two folders. I have made the following script but nothing is copied. My sample batch file is as follows:
FOR /L %%A IN (1,1,2) DO (
xcopy /s C:\Users\abc\def\folder3 C:\Users\xyz\folder%%A
)
is there anything wrong in the batch file?
xcopy /s C:\Users\abc\def\folder3\*.* C:\Users\xyz\folder%%A\
where *.* is an appropriate filemask and the final \ in the destination name tells cmd that the destination is a directory.
I suggest using this command line in the batch file:
for /L %%A in(1,1,2) do %SystemRoot%\System32\xcopy.exe "C:\Users\abc\def\folder3" "C:\Users\xyz\folder%%A\" /C /G /H /I /K /R /Q /S /Y >nul
I enclosed both directory paths in double quotes in case of real paths contain 1 or more spaces or other special characters which require double quotes. The last paragraph on last help page output by running in a command prompt window cmd /? outputs on which characters in a directory/file name double quotes are required around the complete directory/file name.
The target path ends with a backslash to make it clear for console application xcopy that the target is a directory and not a file. Together with the redundant /I the target directory is created if not existing already.
For details on the options used on xcopy open a command prompt window and run xcopy /?. This outputs the help for this console application in the command prompt window. On Windows running a command or console application with /? as parameter outputs in general the help for the command/application.
Note: The copying from one user profile directory to another user profile directory requires local administrator privileges. Each user profile directory is by default protected for exclusive usage of the owning user. Therefore I suggest to open a command prompt window and execute in this window:
for /L %A in(1,1,2) do %SystemRoot%\System32\xcopy.exe "C:\Users\abc\def\folder3" "C:\Users\xyz\folder%A\" /C /G /H /I /K /R /S /Y
You can see if that works with just %A as required on command line instead of %%A as required in batch files and without /Q (quiet copying) and without >nul (redirection of success messages to device NUL to suppress them). Or when it does not work, you can see why it does not work as the error message can be viewed on running a command or a batch file from within a command prompt window instead of double clicking on a batch file because the console window keeps open.

Command Prompt Navigation: Navigating To An Unknownly Named Folder

So, is there any way to navigate your command prompt to/through a location which's name you don't know exactly?
For example the situation is i want to rename the sei.dat file and its located at:
C:/programdata/CsD2/Tools/("THE UNKNOWN VERSION NAMED FOLDER")/data/per/sei.dat
So as you can see i know where the software is installed however the folder after "Tools" folder is named after the version of the tools (example V0.1.2.6) and it changes often.
Is there any command or way to navigate the Command Prompt to the files location? Or if not is there any way to modify the file without navigating the Command Prompt to the location?
I just want to rename the file but i don't know the name of the folder marked as "THE UNKNOWN VERSION NAMED FOLDER"
Test this:
#echo off
for /f "delims=" %%a in ('dir /b /s /a-d "C:\programdata\CsD2\Tools\sei.dat" ') do set "folder=%%~dpa"
if not defined folder echo sei.dat was not found & pause & goto :EOF
cd /d "%folder%"
cmd /k

How to solve "The directory is not empty" error when running rmdir command in a batch script?

I am making a batch script and part of the script is trying to remove a directory and all of its sub-directories. I am getting an intermittent error about a sub-directory not being empty. I read one article about indexing being the culprit. I disabled WSearch but I eventually got the error again. Here's the command:
rmdir /S /Q "C:\<dir>\"
I experienced the same issues as Harry Johnston has mentioned. rmdir /s /q would complain that a directory was not empty even though /s is meant to do the emptying for you! I think it's a bug in Windows, personally.
My workaround is to del everything in the directory before deleting the directory itself:
del /f /s /q mydir 1>nul
rmdir /s /q mydir
(The 1>nul hides the standard output of del because otherwise, it lists every single file it deletes.)
I'm familiar with this problem. The simplest workaround is to conditionally repeat the operation. I've never seen it fail twice in a row - unless there actually is an open file or a permissions issue, obviously!
rd /s /q c:\deleteme
if exist c:\deleteme rd /s /q c:\deleteme
I just encountered the same problem and it had to do with some files being lost or corrupted. To correct the issue, just run check disk:
chkdsk /F e:
This can be run from the search windows box or from a cmd prompt. The /F fixes any issues it finds, like recovering the files. Once this finishes running, you can delete the files and folders like normal.
enter the Command Prompt as Admin and run
rmdir /s <FOLDER>
I had a similar problem, tried to delete an empty folder via windows explorer. Showed me the not empty error, so I thought I try it via admin cmd, but none of the answers here helped.
After I moved a file into the empty folder. I was able to delete the non empty folder
As #gfullam stated in a comment to #BoffinbraiN's answer, the <dir> you are deleting itself might not be the one which contains files: there might be subdirectories in <dir> that get a "The directory is not empty" message and the only solution then would be to recursively iterate over the directories, manually deleting all their containing files... I ended up deciding to use a port of rm from UNIX. rm.exe comes with Git Bash, MinGW, Cygwin, GnuWin32 and others. You just need to have its parent directory in your PATH and then execute as you would in a UNIX system.
Batch script example:
set PATH=C:\cygwin64\bin;%PATH%
rm -rf "C:\<dir>"
Im my case i just moved the folder to root directory like so.
move <source directory> c:\
And then ran the command to remove the directory
rmdir c:\<moved directory> /s /q
I had "C:\Users\User Name\OneDrive\Fonts", which was mklink'ed ( /D ) to "C:\Windows\Fonts", and I got the same problem. In my case
cd "C:\Users\User Name\OneDrive"
rd /s Fonts
Y (to confirm the action)
helped me. I hope, that it helps you too ;D
What worked for me is the following. I appears like the RMDir command will issue “The directory is not empty” nearly all the time...
:Cleanup_Temporary_Files_and_Folders
Erase /F /S /Q C:\MyDir
RMDir /S /Q C:\MyDir
If Exist C:\MyDir GoTo Cleanup_Temporary_Files_and_Folders
The reason rd /s refuses to delete certain files is most likely due to READONLY file attributes on files in the directory.
The proper way to fix this, is to make sure you reset the attributes on all files first:
attrib -r %directory% /s /d
rd /s %directory%
There could be others such as hidden or system files, so if you want to play it safe:
attrib -h -r -s %directory% /s /d
rd /s %directory%
Windows sometimes is "broken by design", so you need to create an empty folder, and then mirror the "broken folder" with an "empty folder" with backup mode.
robocopy - cmd copy utility
/copyall - copies everything
/mir deletes item if there is no such item in source a.k.a mirrors source with
destination
/b works around premissions shenanigans
Create en empty dir like this:
mkdir empty
overwrite broken folder with empty like this:
robocopy /copyall /mir /b empty broken
and then delete that folder
rd broken /s
rd empty /s
If this does not help, try restarting in "recovery mode with command prompt" by holding shift when clicking restart and trying to run these command again in recovery mode
one liner:
if exist folder rmdir /Q /S folder
I'm using this in a NPM script like so (Javascript) :
//package.json
"scripts": {
"start": "parcel --no-cache",
"clean": "if exist dist rmdir /Q /S dist",
"deploy": "npm run clean && parcel build --no-source-maps && firebase deploy"
},
Open CMD as administrator
chkdsk c: /F /R
Press the “Y” key if asked to check your disk the next time your system restarts.
Restart the machine. After that just delete the folder.
The easiest way I found to do this is:
rm -rf dir_name
it worked on zsh - macOS, it should work on windows cmd as well.
if you need to delete a folder on Windows with a batch file you will need to use PowerShell and this is how it is done:
rmdir .\directory_name\ -Recurse
Similar to Harry Johnston's answer, I loop until it works.
set dirPath=C:\temp\mytest
:removedir
if exist "%dirPath%" (
rd /s /q "%dirPath%"
goto removedir
)
Force delete the directory (if exists)
Delete.bat
set output_path="C:\Temp\MyFolder"
if exist %output_path% (
echo Deleting %output_path%
attrib -r /s /d %output_path%
rd /s /q %output_path%
)
I've fixed this before my making sure there wasn't extra whitespace in the name of the directory I was deleting. This is more of a concern when I had the directory name contained within a variable that I was passing to RD. If you're specifying your directly in quotes then this isn't helpful, but I hope that someone like me comes along with the same problem and sees this. RD /S /Q can work, as I noticed the issue started happening when I changed something in my batch script.
I can think of the following possible causes:
there are files or subdirectories which need higher permissions
there are files in use, not only by WSearch, but maybe by your virus scanner or anything else
For 1.) you can try runas /user:Administrator in order to get higher privileges or start the batch file as administrator via context menu. If that doesn't help, maybe even the administrator doesn't have the rights. Then you need to take over the ownership of the directory.
For 2.) download Process Explorer, click Find/Find handle or DLL... or press Ctrl+F, type the name of the directory and find out who uses it. Close the application which uses the directory, if possible.

Problems working with different drive units in a batch file

This is my first batch file, and also my first time with batch language (I usually use UNIX and don't know a lot about Windows commands).
I'm creating a batch file called install.bat which does all the work to install a Java application from source files. Here a snapshot of the install section:
#ECHO off
SET INSTALL_DIR=%1\
SET SRC_DIR=sources\
SET LIB_DIR=lib\
SET IMG_DIR=img\
SET BIN_DIR=bin\
SET INIT_DIR=%CD%
SET MAIN_CLASS=%SRC_DIR%\main\Main.java
SET CLASS_PATH=%LIB_DIR%log4j.jar;%LIB_DIR%jdom.jar;
SET JAR_NOM=myApp.jar
SET JAR_MF=MANIFEST.MF
:BEGIN
CLS
ECHO Checking directory...
IF EXIST %INSTALL_DIR% (
GOTO Ask_Overwrite
) ELSE (
GOTO Install
)
:Ask_overwrite
SET OVERW=Y
SET /P OVERW="The program is already installed. Overwrite? ([Y]/N): "
IF %OVERW%==N GOTO Cancel
IF %OVERW%==n GOTO Cancel
IF %OVERW%==Y (
RD /S /Q %INSTALL_DIR% <--- Here was the error
GOTO Install
)
IF %OVERW%==y (
RD /S /Q %INSTALL_DIR% <--- Here was the error
GOTO Install
)
GOTO Ask_overwrite
:Install
MD %INSTALL_DIR%
XCOPY . %INSTALL_DIR% /E
CD /D %INSTALL_DIR%
MD %BIN_DIR%
ECHO Compiling...
javac -cp %CLASS_PATH% -sourcepath %SRC_DIR% %MAIN_CLASS% -d %BIN_DIR%
ECHO Creating JAR file...
jar cfm %JAR_NOM% %JAR_MF% -C %BIN_DIR% .
ECHO Succes! The application has been installed in %INSTALL_DIR%
GOTO CleanUp
:Abort
ECHO Abort! The application has not been installed.
GOTO CleanUp
:Cancel
ECHO Canceled by user. The application has not been installed.
GOTO END
:Cleanup
REM Code for clean up
GOTO END
:END
CD /D %INIT_DIR%
PAUSE
NOTE: The javac and jar commands are correct, at least work in my machine.
Well, the script works correctly when I test it with the INSTALL_DIR belonging to the same drive where I execute it, but if I use a target directory out of the drive where I'm executing, I have problems.
Executions without problems (called in a cmd.exe session):
C:\Users\TC\testInstall> install.bat .\..\installTarget
C:\Users\TC\testInstall> install.bat C:\Users\TC\installTarget
Execution with problems (called in a cmd.exe session):
C:\Users\TC\testInstall> install.bat D:\Documents\installTarget
The problems happen when I try to copy files specially, but also making and removing directories.
I hope someone can tell to me which options I must use in order to fix the problems.
Regards!
Well, I have two mistakes that I fixed and then the script work correctly.
The first was that I didn't use the /d option in cd command in order to change also the drive unit. It means, C:Users\TC> cd D:\Documents is wrong, the correct command is the following: C:Users\TC> cd /d D:\Documents as well as the MS-DOS manual page indicates.
The second error, it wasn't actually an error, I put rm -rf %INSTALL_DIR% (like in Linux) instead of the correct Windows command rd /s/q %INSTALL_DIR%
Now all the problems have been fixed and the script works properly :)
It has to do with batch files not accessing other drives than the C:\ drive by default. Even if you open up your command line, you shouldn't be able to CD D:\. Try this (not sure if this will work as I have never tried it)
PUSHD D:\
C:\Users\TC\testInstall> install.bat D:\Documents\installTarget
Or else, use PUSHD D:\ then move the install file to D:\ temporarily and install. Only solutions I can think of.

Resources