Auto Open ZIP File Contents After Download - windows

I'm trying to write a batch file that will be executed by a filewatcher once a zip file is downloaded. After download the file is unzipped with the same name, then the zip file is deleted leaving only the file folder and a single PDF file inside. I just need the command to complete this action for the same file that is unzipped.
7z x -oC:\Users\"user"\Downloads\* C:\Users\"user"\Downloads\*.zip
del C:\Users\"user"\Downloads\*.zip
"command opening the file in the unzipped folder"
exit

#echo off
setlocal
:: Start in this dir.
cd /d "%userprofile%\Downloads" || exit /b 1
:: Dir where 7z extracts to.
set "extractdir=unzip_tmp"
:: Zips move here if files or folders exist in cd.
set "faildir=unzip_fail"
rem Continue only if zip files exist.
if not exist *.zip (
echo No zip files
exit /b 0
)
for %%A in (*.zip) do (
set "fail="
rem Unzip with 7z.
echo Unzip: "%%~nxA"
7z x -o"%extractdir%" "%%~nxA" >nul
if not errorlevel 1 (
pushd "%extractdir%" && (
rem Check if files or folders exist in parent dir.
for /f "delims=" %%B in ('dir /b') do (
if exist "..\%%~B" (
echo Exist: "..\%%~B"
set "fail=defined"
)
)
rem Open PDF file.
for /r %%B in (*.pdf) do (
echo Open: "%%~nxB"
start "" /wait "%%~fB"
)
rem Move files or folders to parent dir.
if not defined fail for /f "delims=" %%B in ('dir /b') do (
echo Move: "%%~B"
move "%%~B" .. >nul
)
popd
)
rem Cleanup.
if defined fail (
if not exist "%faildir%" (
echo Create: "%faildir%"
md "%faildir%"
)
echo Remove: "%extractdir%"
rd "%extractdir%" /s /q
echo Move: "%%~nxA"
move "%%~nxA" "%faildir%" >nul
) else (
echo Remove: "%%~nxA"
del "%%~nxA" >nul
)
)
)
rem Final cleanup.
if exist "%extractdir%" (
echo Remove: "%extractdir%"
rd "%extractdir%" /s /q
)
This uses a preset directory to extract the zip files to.
The variable named extractdir has the name of the folder to use.
A preset directory allows the ability to search for PDF files in
an isolated path.
The script is quite verbal so can see what is unzipped, moved etc.
Code operation:
Change directory to Downloads directory.
Exit if no zip files.
Search for zip file.
Extract from zip file to %extractdir%.
Check if extracted files and folders exist in parent directory.
If so, set fail to defined.
Search recursively for PDF files and open them.
if fail is not defined, move files and folders to parent directory.
Cleanup by deleting zip file or removing %extractdir%
and moving the zip file to %faildir% if fail is defined.
Finally remove %extractdir% if exist so it cannot foul up next run.

Use FOR, if you have multiple zip files, it will iterate over them all.
#echo off
for %%I in ("%UserProfile%\Downloads\*.zip") do (
"%ProgramFiles%\7-Zip\7z.exe" e -aoa "-o%%~dpI" -y -- "%%I"
if not errorlevel 1 (
del "%%I"
if exist "%%~dpnI.pdf" start "" "%%~dpnI.pdf"
)
)
This script says, here is the download path. For each PDF in this path, unzip and then delete the zip, open any PDF that was unzipped.

For those that want to try a fast one liner without dependencies this will depend on the file monitor calling the cmd line (as many can do)
you can add a command to go to a working download directory as required then for example if this page was in the zip as PDF run
forfiles /m *.zip /C "cmd /c md #fname && move #fname.zip #fname && cd /d #fname && tar -mxf #fname.zip && start \"\" #fname.pdf"
To delete the zip add && del #fname.zip onto the end of above before the last "
There should be little need for error checks as its conditional && so should not overwrite, the first abort should be
A subdirectory or file blah blah already exists.

Related

How do I output the results of a batch file into a folder with the same name as the input file?

I am currently using a batch file which uses a programm called CriPackTools to extract the contents of a CPK file.
#echo off
for /r %%i in (*.cpk) do "CriPakTools.exe" "%%i" ALL
as you can see here it uses any cpk i drag onto the batch file and extracts the contents to the same directory.
Now how can I change it so it uses my XXXX.cpk, creates a folder named XXXX (the same as the file) and extracts its contents inside the folder.
Thanks
Assuming that the CriPakTools.exe extracting files into a current directory:
#echo off
for /r %%i in (*.cpk) do (
md "%%~dpni"
pushd "%%~dpni"
"CriPakTools.exe" "%%i" ALL
popd
)
Since you are using for /R loop, you are looping through all subfolders. If a .cpk file is located in a folder different than the %cd% or the location of CriPakTools.exe, then the command will fail. I would suggest the following code:
#echo off
pushd "C:\path\with\cpks"
for /R "C:\path\with\cpks" %%A IN (*.cpk) do (
cd "%%~dpA"
mkdir "%%~nA"
cd %%~nA
"CriPakTools.exe" "%%~fA" ALL
)
cd "C:\path\with\cpks"
echo The operation has finished.
pause>nul
exit /b 0
This, may help you.

Copy the same .py file into different folders

I have a simple task which I want to perform in cmd. I have a python file named Export_Excel.py stored in D:\Getting_Started_PyCharm\pyradiomics which I want to copy in many directories.
More specifically I have 30 directories which are inside a folder called NRRD and they are called:
1_patient, 2_patient, ..., 30_patient
Is there a way to do this with a for loop and the copy function in cmd??
Thanks a lot in advance
rem You should replace "" with NRRD's path in the file
set temppath=""
FOR /R %temppath% %%G in (.) DO (
Pushd %%G
copy D:\Getting_Started_PyCharm\pyradiomics\Export_Excel.py %%G
Popd )
echo Copying is done.
Example for PUSHD and POPD
C:\Program Files> PUSHD c:\utils
C:\utils> PUSHD c:\Windows
C:\Windows>
C:\Windows> POPD
C:\utils>
C:\utils> POPD
C:\Program Files>
This is the updated code:
Save this file in notepad as forcopy.bat and run it from the folder.
set temppath=C:\Users\tommaso\Desktop\Lavoro\Zurich_Fellowship\Myocardial_Infarction_DICOM_Images_19_04 _Copia\NRRD
cd %temppath%
for /r %temppath% %%G IN (.) DO (
Pushd %%G
copy "C:\Users\tommaso\Desktop\Excel_Export.py" %%G
Popd
)
del Excel_Export.py
cls
Echo Copying is done
pause
rem //Pause is to pause the execution and wait until the user presses a key.//
In the end, I found a python alternative which is even easier:
import os
from shutil import copy
path_to_file = "/.../.../Export_Excel.py"
path_destination_folder = "/.../.../NRRD/"
for sub_folders in os.listdir(path_destination_folder):
copy(path_to_file, os.path.join(path_destination_folder, sub_folders))

Searching for string in multiple zip archives

Here's what I have;
On a windows-based web server there are roughly 1,000 zip files, each with dozens of log files inside. I already have a script that goes through each archive and deletes all but one specific file type (in an attempt to save diskspace and delete things I don't need). Then, the script unzips each archive to their own folder. And I know how to code the reverse of that to zip them back when I'm done.
Here's what I need to figure out;
Once I run the previously mentioned script (we call it garbageman because it cleans out the garbage in the zip files) I need to go through the remaining 5 or 6 files in each of the newly created unzipped folders, and look for a specific string in each file. If I find the string, I delete everything that is not that string, and save it to a file called "export.txt" in that folder. Then, I move to the next unzipped file, and so on. Once completed, I need re-zip everything back together into their own archives
Here's what I have for code so far. Any help is extremely appreciated.
cd "C:\Program Files\7-Zip"
FOR %%c in (C:\Users\xxxxxx\Desktop\LogQueue\*.*) DO 7z d %%c "-x!xstore*" -r
FOR /R "C:\Users\xxxxxx\Desktop\LogQueue" %%I in ("*.zip") do (
"%ProgramFiles%\7-Zip\7z.exe" x -y -o"%%~dpnI" "%%~fI"
)
cd "C:\Users\xxxxxxx\Desktop\LogQueue"
FOR /R "C:\Users\xxxxxx\Desktop\LogQueue" %%I in ("*.*") do (
findstr "xxxxxxxx_eReceipt" %%~fI > %%~dpnI\export.txt
pause
)
for /d %%X in (*) do "c:\Program Files\7-Zip\7z.exe" a "%%X.zip" "%%X\"
This is an edit:
This script should do what you want.
Only Change sourcedir and mystring variables.
export.txt will be inside a file called Storage in the root directory of the batch.
:ScriptA
#ECHO ON
MKDIR "%CD%\Storage"
MKDIR "%USERPROFILE%\Desktop\Outx"
GOTO :ScriptB
:ScriptB
::REM ONLY CHANGE
SET "sourcedir=%USERPROFILE%\Desktop\Test"
FOR /R "%sourcedir%\" %%a in (*.txt) do copy "%%a" "%CD%\Storage"
:ScriptC
:ScriptC
#ECHO OFF
SETLOCAL
SET "VARA=%CD%\Storage"
SET "VARB=%USERPROFILE%\Desktop\Out"
::REM ONLY CHANGE
SET "mystring=PUT_STRING_HERE"
FOR %%a IN ("%VARA%\*.txt") DO FINDSTR "%mystring%" "%%a">nul&IF NOT ERRORLEVEL 1 FINDSTR "%mystring%" "%%a">"%VARB%\%%~nxa"
DEL /F "%CD%\Storage\*.txt"
GOTO :ScriptD
:ScriptD
#ECHO ON
COPY /B "%USERPROFILE%\Desktop\Outx\*.txt" "%CD%\Storage\export.txt"
RD /S /Q "%USERPROFILE%\Desktop\Outx"
goto :eof

Batch program to rename and delete files

I am trying to check if there any files with *.del extension in c:\temp1 directory. If found, I need to rename such files to .done in the same x directory and delete the same file present in y directory but they will have .gz extension, please suggest. I am using the script below, but when I run it, it says file not found.
Inputfilename : 20130216.001_visual_sciences_web_feed.out.del
Renamedfilename: 20130216.001_visual_sciences_web_feed.out.done
Filetobedeleted: 20130216.001_visual_sciences_web_feed.out.gz
The script:
#echo off
set "dir=c:\raja\temp1"
set "ext=del"
set "rename=.done"
for /f "delims=" %%a in ('dir /b /a-d /s "%dir%\*.%extension%"^|sort /r') do (
echo FILE: %%~fa
call :rename "%%~fa"
)
pause
goto :eof
Please suggest a solution.
for %%a in ("c:\raja\temp1\*.del") do (
ren "%%~fa" *.done >nul
if exist "c:\temp2\%%~na.gz" del "c:\temp2\%%~na.gz" >nul
)
For each file with .del extensions in source, rename to .done , and if file with same name and .gz extension exists (in temp2, from comments) , delete it

How to remove spaces from file names (in bulk)

How to remove spaces (not replace with underscores) from several thousand files in bulk in Windows? Can I do this from the DOS command?
Currently:
file one.mp3
file two.mp3
All files need to become:
fileone.mp3
filetwo.mp3
Here is a script that can efficiently bulk rename files, stripping all spaces from the name.
:renameNoSpace [/R] [FolderPath]
#echo off
setlocal disableDelayedExpansion
if /i "%~1"=="/R" (
set "forOption=%~1 %2"
set "inPath="
) else (
set "forOption="
if "%~1" neq "" (set "inPath=%~1\") else set "inPath="
)
for %forOption% %%F in ("%inPath%* *") do (
if /i "%~f0" neq "%%~fF" (
set "folder=%%~dpF"
set "file=%%~nxF"
setlocal enableDelayedExpansion
echo ren "!folder!!file!" "!file: =!"
ren "!folder!!file!" "!file: =!"
endlocal
)
)
Assume the script is called renameNoSpace.bat
renameNoSpace : (no arguments) Renames files in the current directory
renameNoSpace /R : Renames files in the folder tree rooted at the current directory
renameNoSpace myFolder : Renames files in the "myFolder" directory found in the current directory.
renameNoSpace "c:\my folder\" : Renames files in the specified path. Quotes are used because path contains a space.
renameNoSpace /R c:\ : Renames all files on the C: drive.
In Windows:
Open a Command Prompt.
Go to the folder with the cd command (eg.: cd "paht of your folder").
Open a powershell by typing: powershell
Then input this: get-childitem *.mp3 | foreach {rename-item $_ $_.name.replace(" ","")}
Create a powershell file - *.ps1 extension
Write this code:
dir |
Where-Object { $_.name.Contains(" ") } |
Rename-Item -NewName { $_.name -replace " ","" }
save, then right click -> run with powershell
Open Powershell in windows and then type the following command after navigating to the folder where you want to rename the files
get-childitem *.mp3 | foreach { rename-item $_ $_.Name.Replace(" ", "") }
Let's Analyze it:
get-childitem *.mp3
This lists all files whose names end with .mp3. They are then piped to the next command with the | operator.
foreach { rename-item $_ $_.Name.Replace(" ", "") }
This replaces all instances of " " (white space in this case || this is the instance which is to be replaced) with nothing, denoted by "", effectively wiping the word from all the files in the directory.
You could also modify get-childitem *.mp3 to get-childitem – that would rename all the files in the directory, not just files whose names end with .mp3.
** Note **
If you do not like the above method there is a awesome software named Bulk Rename Utility. I used this software personally and you can get many tuts on youtube how to use it.
You can write a simple script that does this for one file/directory, e.g.:
#echo off
setlocal enableextensions enabledelayedexpansion
set "ARG=%~1"
ren "%ARG%" "%ARG: =%"
...and then if you'd like, run it over all the files and/or directories you care about. For instance, if you create the above script as myrenamingscript.cmd, you can run it over all non-dir files in the current dir by running:
for %f in (*) do #myrenamingscript.cmd "%~f"
#echo off
setlocal enableextensions enabledelayedexpansion
for %%f in (*.*) do (
set ARG=%%~nxf
rename "%%f" !ARG: =!
)
Since programmatically renaming files is risky (potentially destructive if you get it wrong), I would use a tool with a dry run mode built specifically for bulk renaming, e.g. renamer.
This command strips out the whitespace from all files in the current directory:
$ renamer --find "/\s/g" --dry-run *
Dry run
✔︎ file one.mp3 → fileone.mp3
✔︎ file two.mp3 → filetwo.mp3
Rename complete: 2 of 2 files renamed.
Plenty more renamer usage examples here.
The problem i have faced is that there is a possibility that there is already a file with the name you try to give to the new file (eg if there are 2 files in the folder named "file one.txt" and "file_one.txt" when you try to replace the spaces with underscores, one file will replace the other). So I made this script that checks if the new name already exists and if so places a number at the end of the file name (adds 1 to the number until there is no other file with that name). Instructions about what to change are at the top (commended out lines). Do not store the batch file in the same folder you have the files to be renamed if you use *.* option. I hope this helps.
#echo off
REM Instructions
REM This script repaces spaces from file names with underscores.
REM If you want to just remove the spaces uncomment lines 30 and 52 and comment out the lines 29 and 51.
REM set the following parameters.
REM pb is the folder containing the files we want to rename (fullpath)
REM tm is a temporary folder that will be created and deleted. Just put a folder that does not exist and is not used by anything else (fullpath).
REM all is the file type you want to raname. E.g. *.* for every file, *.txt for TXTs, *.pdf for PDFs etc
REM you don't have to change anything else
set pb=<folder containing the files to rename>
set tm=<a temp folder that does not exist>
set all=*.*
set pa=%pb%%all%
setlocal EnableDelayedExpansion
cd /d %pa%
set /a count=1
if not exist %tm% mkdir %tm%
for /f %%F in (%pa%) do (
set name=%%~nF
set name2=!name: =_!
REM set name2=!name: =!
set name3=!name2!%%~xF
if !name2! == %%~nF (
move /y %%~dpF\!name3! %tm%\ >nul
) else (
if not exist %%~dpF\!name3! (
if not exist %tm%\!name3! (
ren "%%F" "!name3!"
move /y %%~dpF\!name3! %tm%\ >nul
)
)
)
)
:rename
for /f %%F in (%pa%) do (
set name=%%~nF
set name2=!name: =_!
REM set name2=!name: =!
set name4=!name2!%count%
set name3=!name4!%%~xF
if !name2! == %%~nF (
move /y %%~dpF\!name3! %tm%\ >nul
) else (
if not exist %%~dpF\!name3! (
if not exist %tm%\!name3! (
ren "%%F" "!name3!"
move /y %%~dpF\!name3! %tm%\ >nul
)
)
)
)
set /a count = %count% + 1
set /a loop = 0
for %%F in (%pa%) do (set /a loop = 1)
if %loop% equ 1 goto rename
move /y %tm%\%all% %pb% >nul
rmdir /s /q %tm%
Just copy paste this to batch-file and save as c:\myfolder\r.bat
setlocal EnableDelayedExpansion
#echo off &cls
set p=%*
set p=!p: =!
set p=!p:^(=!
set p=!p:^)=!
set p=!p:^[=!
set p=!p:^]=!
set p=!p:^$=!
set p=!p:^&=!
set p=!p:^#=!
set p=!p:^;=!
set p=!p:^:=!
set p=!p:^,=!
set p=!p:^#=!
set p=!p:^_=!
set p=!p:^-=!
set e=%p:~-4%
ren "%*" %time:~6,2%%time:~9,2%%e%
exit
Add a registry ket at
Windows Registry Editor Version 5.00
[HKEY_CLASSES_ROOT\*\shell\#myRENAME]
#=""
[HKEY_CLASSES_ROOT\*\shell\#myRENAME\command]
#="c:\myfolder\r.bat \"%1\""
done, now select files & just right-click select myRENAME
all the files will be renamed instantly.

Resources