cmd – Changing all files’ extensions in a folder with one command on Windows – Stack Overflow

An easier way to recover deleted partition in windows 7/8/10

To recover deleted partition with an easier, you can empoly AOMEI Partition
Assistant Professional. Compared with CMD, it’s easier to learn and operate.

AOMEI Partition Assistant can be used to do more things, such as, delete EFI system
partition, move
partition to end of disk, convert GPT disk to MBR, etc.

If you need to use AOMEI Partition Assistant on Windows Server, you can  AOMEI Partition
Assistant Server.

See the detailed steps and learn how to easily recover data lost by Diskpart
clean.

Step 1. Find the deleted partition in Disk Management.

Step 2. Run AOMEI Partition Assistant Professional and
enjoy it.

Step 3. Click Partition Recovery Wizard on
the left panel. Select the disk containing deleted partition and click Next.

Step 4. Select Fast Search. This option
takes less time. If you cannot recover the deleted partition for the first time, you
can try Partition Recovery Wizard again and select Full Search.

Step 5. Select the deleted partition to recover and click Next.
To ensure the deleted partition, you can tick the partition and click Explore
files in this selected partition to confirm.

Step 6.When you see Congratuations! Click Finish to exit the
progress, and you can go to Disk Management or File Explorer to find the lost
partition.

Bat file to run a .exe at the command prompt

What’s stopping you?

Put this command in a text file, save it with the .bat (or .cmd) extension and double click on it…

Presuming the command executes on your system, I think that’s it.

Changing all files’ extensions in a folder with one command on windows

Rename multiple file extensions:

You want to change ringtone1.mp3, ringtone2.mp3 to ringtone1.wav, ringtone2.wav

Here is how to do that:
I am in d drive on command prompt (CMD) so I use:

d:>ren *.* *.wav 

This is just an example of file extensions, you can use any type of file extension like WAV, MP3, JPG, GIF, bmp, PDF, DOC, DOCX, TXT this depends on what your operating system.

And, since you have thousands of files, make sure to wait until the cursor starts blinking again indicating that it’s done working.

Delete folder from cmd

Run the command rmdir on the folder.

rmdir directoryname

Example:

C:>rmdir emptydir
C:>

Delete locked files

Typically this is caused by the Offline Cache or Internet Explorer temp files.

Close all applications
Open a command prompt
Click Start, and then Shut Down
Simultaneously press CTRL SHIFT ALT.
While you keep these keys pressed, click Cancel in the Shut Down Windows dialog
box.
In the command prompt window, navigate to the cache location, and delete all
files from the folder (DEL /s)
At the command prompt, type explorer, and then press ENTER.

DELTREE –
Older versions of Windows had the DELTREE command to delete all files and sub folders. This can be replicated with a script as shown on the DELTREE page.

Examples:

Delete “Hello World.txt”

DEL “Hello World.txt”

Delete 3 named files:

DEL file1.txt file2.txt “C:demofile3.txt”

Delete all files that start with the letter A

DEL A*

Delete all files that end with the letter A

DEL *A.*

Delete all files with a .doc extension:

DEL *.doc

Delete all read only files:

DEL /a:R *

Delete all files including any that are read only:

DEL /F *

Normally DEL will display a list of the files deleted, if Command Extensions are disabled; it will instead display a list of any files it cannot find.

DEL is an internal command. ERASE is a synonym for DEL

“It devoured my paper, it was a really good paper” – Ellen Feiss

Deleting directory with white spaces in the name

Rmdir can delete files with whitespaces in the name, you just need to wrap up the folder name in double quotes as shown in the below example.

rmdir /Q /S "folder with spaces in the name"

Errorlevels

If the files were successfully deleted %ERRORLEVEL% = 0
If the files failed to delete, or don’t exist to be deleted %ERRORLEVEL% = 0
Bad or no parameters given %ERRORLEVEL% = 1

Errors

To delete a directory, you should have appropriate access permissions on the directory. Otherwise rmdir throws ‘Access denied’ error.

Force delete a folder without confirmation

To  force delete directory, without being asked for confirmation, we can use /Q switch.

rmdir /Q /S nonemptydir

How to delete all files and folders in a folder by cmd call

No, I don’t know one.

If you want to retain the original directory for some reason (ACLs, &c.), and instead really want to empty it, then you can do the following:

del /q destination*
for /d %x in (destination*) do @rd /s /q "%x"

This first removes all files from the directory, and then recursively removes all nested directories, but overall keeping the top-level directory as it is (except for its contents).

Note that within a batch file you need to double the % within the for loop:

del /q destination*
for /d %%x in (destination*) do @rd /s /q "%%x"

How to delete files/subfolders in a specific directory at the command prompt in windows

None of the answers as posted on 2021-06-01, with the exception of the single command line posted by foxidrive, really deletes all files and all folders/directories in %PathToFolder%. That’s the reason for posting one more answer with a very simple single command line to delete all files and subfolders of a folder as well as a batch file with a more complex solution explaining why all other answers as posted on 2021-06-01 using DEL and FOR with RD failed to clean up a folder completely.


The simple single command line solution which of course can be also used in a batch file:

pushd "%PathToFolder%" 2>nul && ( rd /Q /S "%PathToFolder%" 2>nul & popd )

This command line contains three commands executed one after the other.

:/>  Устранение проблемы со сменой языковой раскладки клавиатуры в Windows 7

The first command PUSHD pushes current directory path on stack and next makes %PathToFolder% the current directory for running command process.

This works also for UNC paths by default because of command extensions are enabled by default and in this case PUSHD creates a temporary drive letter that points to that specified network resource and then changes the current drive and directory, using the newly defined drive letter.

PUSHD outputs following error message to handle STDERR if the specified directory does not exist at all:

The system cannot find the path specified.

This error message is suppressed by redirecting it with 2>nul to device NUL.

The next command RD is executed only if changing current directory for current command process to specified directory was successful, i.e. the specified directory exists at all.

The command RD with the options /Q and /S removes a directory quietly with all subdirectories even if the specified directory contains files or folders with hidden attribute or with read-only attribute set. The system attribute does never prevent deletion of a file or folder.

Not deleted are:

  1. Folders used as the current directory for any running process. The entire folder tree to such a folder cannot be deleted if a folder is used as the current directory for any running process.

  2. Files currently opened by any running process with file access permissions set on file open to prevent deletion of the file while opened by the running application/process. Such an opened file prevents also the deletion of entire folder tree to the opened file.

  3. Files/folders on which the current user has not the required (NTFS) permissions to delete the file/folder which prevents also the deletion of the folder tree to this file/folder.

The first reason for not deleting a folder is used by this command line to delete all files and subfolders of the specified folder, but not the folder itself. The folder is made temporarily the current directory for running command process which prevents the deletion of the folder itself. Of course this results in output of an error message by command RD:

The process cannot access the file because it is being used by another process.

File is the wrong term here as in reality the folder is being used by another process, the current command process which executed command RD. Well, in reality a folder is for the file system a special file with file attribute directory which explains this error message. But I don’t want to go too deep into file system management.

This error message, like all other error messages, which could occur because of the three reasons written above, is suppressed by redirecting it with 2>nul from handle STDERR to device NUL.

The third command, POPD, is executed independently of the exit value of command RD.

POPD pops the directory path pushed by PUSHD from the stack and changes the current directory for running the command process to this directory, i.e. restores the initial current directory. POPD deletes the temporary drive letter created by PUSHD in case of a UNC folder path.

Note:POPD can silently fail to restore the initial current directory in case of the initial current directory was a subdirectory of the directory to clean which does not exist anymore. In this special case %PathToFolder% remains the current directory. So it is advisable to run the command line above not from a subdirectory of %PathToFolder%.

One more interesting fact:
I tried the command line also using a UNC path by sharing local directory C:Temp with share name Temp and using UNC path \%COMPUTERNAME%TempCleanTest assigned to environment variable PathToFolder on Windows 7. If the current directory on running the command line is a subdirectory of a shared local folder accessed using UNC path, i.e. C:TempCleanTestSubfolder1, Subfolder1 is deleted by RD, and next POPD fails silently in making C:TempCleanTestSubfolder1 again the current directory resulting in Z:CleanTest remaining as the current directory for the running command process. So in this very, very special case the temporary drive letter remains until the current directory is changed for example with cd /D %SystemRoot% to a local directory really existing. Unfortunately POPD does not exit with a value greater 0 if it fails to restore the initial current directory making it impossible to detect this very special error condition using just the exit code of POPD. However, it can be supposed that nobody ever runs into this very special error case as UNC paths are usually not used for accessing local files and folders.

For understanding the used commands even better, open a command prompt window, execute there the following commands, and read the help displayed for each command very carefully.

Single line with multiple commands using Windows batch file explains the operators && and & used here.


Next let us look on the batch file solution using the command DEL to delete files in %PathToFolder% and FOR and RD to delete the subfolders in %PathToFolder%.

@echo off
setlocal EnableExtensions DisableDelayedExpansion

rem Clean the folder for temporary files if environment variable
rem PathToFolder is not defined already outside this batch file.
if not defined PathToFolder set "PathToFolder=%TEMP%"

rem Remove all double quotes from folder path.
set "PathToFolder=%PathToFolder:"=%"

rem Did the folder path consist only of double quotes?
if not defined PathToFolder goto EndCleanFolder

rem Remove a backslash at end of folder path.
if "%PathToFolder:~-1%" == "" set "PathToFolder=%PathToFolder:~0,-1%"

rem Did the folder path consist only of a backslash (with one or more double quotes)?
if not defined PathToFolder goto EndCleanFolder

rem Delete all files in specified folder including files with hidden
rem or read-only attribute set, except the files currently opened by
rem a running process which prevents deletion of the file while being
rem opened by the application, or on which the current user has not
rem the required permissions to delete the file.
del /A /F /Q "%PathToFolder%*" >nul 2>nul

rem Delete all subfolders in specified folder including those with hidden
rem attribute set recursive with all files and subfolders, except folders
rem being the current directory of any running process which prevents the
rem deletion of the folder and all folders above, folders containing a file
rem opened by the application which prevents deletion of the file and the
rem entire folder structure to this file, or on which the current user has
rem not the required permissions to delete a folder or file in folder tree
rem to delete.
for /F "eol=| delims=" %%I in ('dir "%PathToFolder%*" /AD /B 2^>nul') do rd /Q /S "%PathToFolder%%%I" 2>nul

:EndCleanFolder
endlocal

The batch file first makes sure that environment variable PathToFolder is really defined with a folder path without double quotes and without a backslash at the end. The backslash at the end would not be a problem, but double quotes in a folder path could be problematic because of the value of PathToFolder is concatenated with other strings during batch file execution.

:/>  Как запускать файлы .BAT незаметно, без отображения окна командной строки

Important are the two lines:

del /A /F /Q "%PathToFolder%*" >nul 2>nul
for /F "eol=| delims=" %%I in ('dir "%PathToFolder%*" /AD /B 2^>nul') do rd /Q /S "%PathToFolder%%%I" 2>nul

The command DEL is used to delete all files in the specified directory.

The commands FOR and RD are used to remove all subdirectories in specified directory. But for /D is not used because of FOR is ignoring in this case subdirectories with the hidden attribute set. For that reason for /F is used to run the following command line in a separate command process started in the background with %ComSpec% /c:

dir "%PathToFolder%*" /AD /B 2>nul

DIR outputs in bare format because of /B the directory entries with attribute D, i.e. the names of all subdirectories in specified directory independent on other attributes like the hidden attribute without a path. 2>nul is used to redirect the error message output by DIR on no directory found from handle STDERR to device NUL.

The redirection operator > must be escaped with the caret character, ^, on the FOR command line to be interpreted as a literal character when the Windows command interpreter processes this command line before executing the command FOR which executes the embedded dir command line in a separate command process started in the background.

FOR processes the captured output written to handle STDOUT of a started command process which are the names of the subdirectories without path and never enclosed in double quotes.

FOR with option /F ignores empty lines which don’t occur here as DIR with option /B does not output empty lines.

FOR would also ignore lines starting with a semicolon which is the default end of line character. A directory name can start with a semicolon. For that reason eol=| is used to define the vertical bar character as the end-of-line character which no directory or file can have in its name.

FOR would split up the line into substrings using space and horizontal tab as delimiters and would assign only the first space/tab delimited string to specified loop variable I. This splitting behavior is not wanted here because of a directory name can contain one or more spaces. Therefore delims= is used to define an empty list of delimiters to disable the line splitting behavior and get assigned to the loop variable, I, always the complete directory name.

Command FOR runs the command RD for each directory name without a path which is the reason why on the RD command line the folder path must be specified once again which is concatenated with the subfolder name.

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.

How to input a text file into an exe through cmd?

Trying to use my program to take a stdin through the cmd.

For example, I have a program that takes in a number from user input using scanf.

How do I use the console to redirect the input.

I’ve tried program.exe < input.txt, but I get an error that the file specified is not found.

When I run the exe and type <input.txt, it outputs a single line of what I assume to be a memory address.

edit:
Figured out the input, however getting an unexpected output.

 #define SIZE 5
    int main(){

    int i,j,num, row[SIZE];
    char line[SIZE 1];


    scanf("%d", &num);
    printf("%d", num);

    for(i=0;i<num;i  ){

        scanf("%s", line);

        for (i=0; i<SIZE; i  )

             arr[i] = line[i] - '0';

        printf("%d",arr);

What it’s meant to do is take in a number of lines to variable num.

From there, it should can the all lines and take a string of numbers, then put that string of numbers into an array of int.

E.g. input

1
28374

e.g. output

28374

Which should really be

arr[0]=2,
arr[1]=8,
arr[2]=3,
and so on

.

How to recover deleted partition using cmd?

Sometimes, loss of volume label, drive letter, partition name or Diskpart clean
command can result in partition loss issue. If these happen to the causes of
partition loss, you can try to assign drive letter using Diskpart. This operation
can undo Diskpart clean using CMD.

Step 1. Find the deleted partition in Disk Management.

1. Press Win R to summon the Run window.

2.Type diskmgmt.msc in the pop-up window
and then press OK to open Disk Management.

3. Find the deleted partition and remember its partition size.
Usually, the deleted partition will be marked as Unallocated.

Julia – how to open a file using a cmd type?

I am trying to physically open a file (not to read the data but just open it in windows) in Julia.

:/>  dos - If not exists then exit cmd - Stack Overflow

I have tried using run(`test.txt`) but it could not find the file. Then I realized that I needed a command in front so I tried run(`run test.txt`). This seems to find the file but the file crashes immediately upon startup. How should I go about opening this file? Thanks.

Matters you should pay attention to

As mentioned above, the system just removes partition information instead of
completely wiping the area occupied by deleted partition.

To ensure you can recover data or partition, pay attention to the following
things.

1. Do to run any operation on this partition.

2. Do not add new items to this partition.

3. Do not reformat this partition.

Openfiles – управление открытыми файлами.

Команда OPENFILES используется для получения списка открытых файлов и папок в среде операционных систем
Windows XP и старше. Возможно получение списка файлов, открытых удаленно с использованием сетевого доступа, или полного списка, включая файлы и папки,
открытые локальными процессами. Кроме того, команда позволяет выполнить отключение сеансов удаленного открытия файлов или каталогов. Для работы с
данной командой требуются права администратора ( “Запуск от имени администратора” в среде Windows 7 и старше)

Формат командной строки:

OPENFILES /параметр [аргументы]

Список параметров:

/Disconnect – Отключение одного и более открытых файлов.

/Query – Отображение открытых файлов, локально и с сетевого ресурса.

/Local – Включает/отключает отображение локально открытых файлов.

/? – Вывод справки.

Для получения справки по использованию команды с конкретным параметром используется
следующий формат командной строки:

OPENFILES /Disconnect /? – отобразить подсказку по использованию команды OPENFILES с параметром /Disconnect

OPENFILES /Query /? | more – выдать подсказку по использованию параметра /Query в постраничном режиме вывода на экран

OPENFILES /Local /? > D:oflocal.txt – выдать подсказку по использованию параметра /Local в текстовый файл D:oflocal.txt

Для управления режимом построения списка открытых файлов используется глобальный переключатель списка объектов (maintain objects list) текущее значение которого можно проверить
командой :

OPENFILES /Local

Если флаг “построение списка объектов” включен, то команда OPENFILES отображает список файлов и папок, открытых как локально, так и по сети. Для отключения режима отображения списка файлов, открытых локальными процессами, используется команда:

openfiles /local off

Для вступления в силу нового режима построения списка открытых файлов, может потребоваться перезагрузка системы.

Список открытых файлов отображается с использованием команды OPENFILES /Query.

Формат командной строки:

OPENFILES /Query [/S система [/U пользователь [/P [пароль]]]] [/FO формат] [/NH] /V]

Список параметров:

/S система – Подключаемый удаленный компьютер.

/U []пользователь – Пользовательский контекст, в котором должна выполняться эта команда.

/P [пароль] – Пароль для этого пользовательского контекста.

/FO формат – Формат, в котором следует отобразить выходной файл. Допустимые форматы: “TABLE”,”LIST”,”CSV”.

/NH – Указывает, что строка заголовков столбцов не должна отображаться. Допустимо только для форматов “TABLE”, “CSV”.

/V – Отображать расширенную информации в результатах.

/? – Вывод справки по использованию.

Примеры:

OPENFILES /Query /? – отобразить справку по использованию команды.

OPENFILES /Query – отобразить список открытых файлов и папок с параметрами по умолчанию.

OPENFILES /Query /FO CSV /NH – отобразить список открытых файлов в формате CSV – полей, разделяемых запятой, без отображения заголовков столбцов ( /NH ).

OPENFILES /Query /FO TABLE /V – отобразить список открытых файлов в виде таблицы (TABLE) с включением дополнительной информации (/V) об имени пользователя и идентификаторе процесса (PID). По умолчанию, используется список в формате таблицы, поэтому параметр /FO TABLE можно не указывать.

OPENFILES /Query /S /U /P – отобразить список открытых файлов на удаленном компьютере, с использованием имени пользователя и пароля, задаваемых в командной строке.

OPENFILES /S SERVER /U mydonainuser1 /P mypass – отобразить список открытых файлов на удаленном компьютере SERVER . Для выполнения команды на удаленном компьютере используется имя пользователя user1 в домене mydomain и пароль mypass. Если имя пользователя и пароль не заданы – используется учетная запись, в контексте которой выполняется команда OPENFILES

OPENFILES /S 192.168.0.1 /U mydonainuser1 /P mypass – то же, что и в предыдущем примере, но вместо имени удаленного компьютера, используется его IP-адрес.

OPENFILES /Query > C:OpenedFiles.txt – записать результаты выполнения команды в текстовый файл C:OpenedFiles.txt

Пример списка открытых файлов, полученного по команде OPENFILES /Query:

Список файлов, открытых локально:
———————-

ID
=====
8
48
8
8
668
. . .
Имя процесса
===============
dwm.exe
dwm.exe
taskhost.exe
explorer.exe
explorer.exe

Permanent deletion

Deleting a file will not prevent third party utilities from un-deleting it again.
Secure file deletion utilities are available, however for casual use, you can turn any file into a zero-byte file to destroy the file allocation
chain like this:

TYPE nul > C:examplesMyFile.txt
DEL C:examplesMyFile.txt

Undeletable files

Files are sometimes created with a very long filename or a trailing period or with reserved names (CON, AUX, COM1, COM2, COM3, COM4, LPT1, LPT2, LPT3, PRN, NUL) and as a result they become impossible to delete with Windows Explorer.

To delete such files use the syntax: DEL “\?path to file”
You can also use
“\.path to device

e,g,
DEL “\?C:some folderAZH64GT.”
DEL “\.C:WorkLPT1

Alternatively for long filenames, you can reduce the total path length by using SUBST to map a drive letter to the folder containing the file.

It is also possible to delete long paths using RoboCopy – Copy/Move the required files to a temporary folder and then delete the folder, one gotcha with that technique is RoboCopy’s tendency to follow symbolic links which can cause files outside the source folder to be moved/ deleted.

If a file is still ‘undeletable’ this may be
caused by the indexing service, temporarily stop the service and then delete the file.

Оставьте комментарий