Windows script to delete everything but image file extensions - powershell

I want to create a script on Windows 7 to delete everything in a directory that is not a picture.
So
for all files in directory X
if file y does not have extension in (.png, .gif, .jpeg)
delete y
end
that's it
how can I find or create such a script
mind you, some pictures are important, so this script has to work correctly :) I don't think I should be experimenting here, and even if I tested my own script on a small directory with experimental files, I am not confident that I should try it.
I have this code as suggested:
::extensions are delimited with space // filename is del_stuff.bat
set "extensions_list=.png .gif .jpeg .bmp .jpg "
pushd "C:\Users\denman\Desktop\xxx\"
for /f "delims=" %%f in ('dir /b ^|findstr /i /e /v "%extensions_list%" ') do (
echo del /q /f "%%~f"
)
popd
But I get this error:

Using Powershell, you can get the list of files you need with something like this:
Get-ChildItem | where {!$_.PsIsContainer -and !(#(".png",".gif",".jpeg") -contains $_.Extension) }
I left the Delete command to you, make sure the list returns correct results before you do it.

#echo off
::extensions are delimited with space
set "extensions_list=.png .gif .jpeg "
pushd "C:\Directory_with_pictures" && (
for /f "delims=" %%f in ('dir /b /a-d ^|findstr /i /e /v "%extensions_list%" ') do (
echo del /q /f "%%~f"
)
popd
)
The 'echo' is to verify the result .remove the echo to activate deletion.And change "C:\Directory_with_pictures" with the actual path.
EDIT testing the script:
#echo off
md test_dir>nul 2>&1
echo #>test_dir\t1.png
echo #>test_dir\t1.txt
echo #>test_dir\t1.tst
echo #>test_dir\t1.jpg
echo #>test_dir\t1.gif
echo #>test_dir\t2.png
echo #>test_dir\t2.txt
echo #>test_dir\t2.tst
echo #>test_dir\t2.jpg
echo #>test_dir\t2.gif
echo -- before deleting--
dir /b .\test_dir\*
echo(
echo(
::extensions are delimited with space
set "extensions_list=.png .gif .jpeg .jpg"
pushd "test_dir"
for /f "delims=" %%f in ('dir /b ^|findstr /i /e /v "%extensions_list%" ') do (
del /q /f "%%~f"
)
popd
echo -- after deleting --
dir /b .\test_dir\*
Output:
-- before deleting--
t1.gif
t1.jpg
t1.png
t1.tst
t1.txt
t2.gif
t2.jpg
t2.png
t2.tst
t2.txt
-- after deleting --
t1.gif
t1.jpg
t1.png
t2.gif
t2.jpg
t2.png

Related

Update file in each subdirectory with a specific name

I have a batch-file which pulls a file from a url using powershell and then outputs/updates the file in a specific directory. But I have many of these directories, the only thing that changes about the path is numbers between \command\ and \setup\. How would I get it to put the file in every folder automatically?
Essentially I would like to output the downloaded text file in each of the install subdirectories of that path.
Also how could I make it happen silently?
#echo off
echo !!! PRESS ANY KEY TO CONTINUE AND UPDATE!!!
pause
powershell -Command "Invoke-WebRequest http://example.com/log/read.txt" -OutFile C:\Users\Administrator\AppData\Roaming\base\command\234235234\setup\install\read.txt 2>NUL >NUL
echo !!! DONE NOW !!!
echo !!! YOU CAN RE-OPEN NOW !!!
for /d /r "dirname" %%a in (*) do if /i "%%~nxa"=="install" echo %%a
may be useful to you.
Your requirement is unclear. Do you want to copy the file to the install subdirectories of ...\234235234\.. only, or of ...\*\... ?
Replace dirname with the name of the starting directory, be it ...\234235234\.. or C:\Users\Administrator\AppData\Roaming\base\command and the command I have shown will report all of the install directories contained under dirname. All you need then do is to change the echo to an appropriate copy command - see copy /? from the prompt. You can suppress copy's responses by appending >nul 2>nul (suppress messages and suppress error messages)
for /d /r with * as the list element will process a list of all subdirectories starting at the nominated directory. The if command selects only the leaf directories that match install in either case (/i)
Since
for /d /r ...
does nor detect hidden directories, another approach is
for /f "delims=" %%a in ('dir /s /b /ad "dirname" ') do if /i "%%~nxa"=="sub1" echo %%a
Which in this case should be
for /f "delims=" %%a in ('dir /s /b /ad "C:\Users\Administrator\AppData\Roaming\base\command" ') do if /i "%%~nxa"=="sub1" echo %%a
The dir command produces a list in /b basic (name-only) form, /s including subdirectories, /ad of directories only (names with the directory attribute set). This list is processed line-by-line by for /f without delimiters so the entire line (including spaces, if any) is assigned to %%a and displayed.

Folder being used for another process on batch script

I have a issue with a backup script I wrote. The backup is pretty simple. It will copy a directory to a destination path, and then zip it. I have a few If clauses to, example, delete the oldest backup if there are 5 or more .zip from previous backups.
The problem I'm facing is: after the XCOPY command has finished running I then run a PowerShell script from my Batch to zip the backup, but I get this error:
This happens becaus the .bat file is running. I've checked.
The code for both the batch and power shell script follows:
BATCH:
echo "========================================="
echo "=====| Backuping DCT Light's Files |====="
echo "========================================="
SET dct-light_src=\\w102xnk172\c$\inetpub\wwwroot\DCT_NEW
For /f "tokens=2-4 delims=/ " %%a in ('date /t') do (set dct_light_startting_date=%%c-%%a-%%b)
For /f "tokens=1-2 delims=/:" %%a in ("%TIME%") do (set dct_light_startting_time=%%a%%b)
SET starttime=%dct_light_startting_date%
CD C:\Users\william_silva4\Desktop\tools_backup\dct_light\
SETLOCAL ENABLEDELAYEDEXPANSION
SET /A "N=0"
FOR /F %%f IN ('DIR /B /A:-D "*"') DO (SET /A "N=!N!+1")
IF %n% == 5 (
powershell.exe -noexit -file "C:\Users\william_silva4\Desktop\remove_oldest.ps1"
) ELSE (
IF EXIST C:\Users\william_silva4\Desktop\tools_backup\dct_light\dctlight_backup_%starttime%\ (
MD C:\Users\william_silva4\Desktop\tools_backup\dct_light\dctlight_backup_%starttime%\dctlight_backup
SET dct-light_dtn=C:\Users\william_silva4\Desktop\tools_backup\dct_light\dctlight_backup_%starttime%\dctlight_backup
echo A folder for this backup already exists. Beggining overwrite...
) ELSE (
MD C:\Users\william_silva4\Desktop\tools_backup\dct_light\dctlight_backup_%starttime%\dctlight_backup
SET dct-light_dtn=C:\Users\william_silva4\Desktop\tools_backup\dct_light\dctlight_backup_%starttime%\dctlight_backup\
)
)
CD C:\Users\william_silva4\Desktop\backup_completo
XCOPY %dct-light_src% %dct-light_dtn% /w /e /y /EXCLUDE:C:\Users\william_silva4\Desktop\backup_completo\exclusion.txt
For /f "tokens=2-4 delims=/ " %%a in ('date /t') do (set dct_light_finished_date=%%c-%%a-%%b)
For /f "tokens=1-2 delims=/:" %%a in ("%TIME%") do (set dct_light_finished_time=%%a%%b)
SET startdate=%dct_light_finished_date%
SET starttime=%dct_light_startting_date%_%dct_light_startting_time%
SET finishedtime=%dct_light_finished_date%_%dct_light_finished_time%
CD C:\Users\william_silva4\Desktop\tools_backup\dct_light\dctlight_backup_%startdate%\
echo.LOG of %starttime%'s Backup>LOG_%startdate%.txt
echo.Start time: %starttime%>>LOG_%startdate%.txt
echo.Finished time: %finishedtime%>>LOG_%startdate%.txt
CD C:\Users\william_silva4\Desktop\tools_backup\dct_light\dctlight_backup_%startdate%\dctlight_backup\
SETLOCAL ENABLEDELAYEDEXPANSION
SET /A "N=0"
FOR /F %%f IN ('DIR /S /B /A:-D "*"') DO (SET /A "N=!N!+1")
CD ../
echo.Files copied: %N%>>LOG_%startdate%.txt
powershell.exe -noexit -file "C:\Users\william_silva4\Desktop\zip_backups.ps1"
pause>nul
POWER SHELL:
#DCT Light's zipping
Start-Sleep -s 15
$source = "C:\Users\william_silva4\Desktop\tools_backup\dct_light"
$date = Get-Date -UFormat "%Y-%m-%d"
$destination = "C:\Users\william_silva4\Desktop\tools_backup\dct_light\dctlight_backup_$date.zip"
If(Test-path $destination) {Remove-item $destination}
Add-Type -assembly "system.io.compression.filesystem"
[io.compression.zipfile]::CreateFromDirectory($source, $destination)
Remove-Item $source\* -Recurse -Exclude *.zip
What I have tried to solve the problem:
Create a Master.ps1 with a list of scripts to run, where the first one is, obliviously, the backup batch file and then the zipping ps1 file.
Call the zipping ps1 file from the backup batch file on another window and then kill the batch. In this case, the first line of the zipping script was:
Start-Sleep -s 15
So I was certain that the batch was killed before I really started zipping.
None of the above worked. Any help? If nothing works I'll just schedule them as separated tasks on Windows.

BAT/POWERSHELL copy (only)yesterday files

I'm trying to write some script to copy all files which have been created yesterday (only!)
/D parameter for xcopy means copy files changed on or after the specified date so its not what i'm searching for. Any ideas? ;/
I suggest you to use powershell. You can use Get-ChildItem and Where-Object to get the list of files created the day before
$yesterdayFiles = Get-ChildItem | Where-Object {$_.CreationTime.Date -eq ((Get-Date).AddDays(-1).Date)}
Then you can copy the files stored in $yesterdayFiles variable using Copy-Item cmdlets
I've tried with robocopy /minage:1 /maxage:1 but seems does not work.But work when I set the current date.Here's the script (you'll need to set your source and destination):
#echo off
set "source=C:\folder1"
set "dest=C:\folder2"
pushd "%temp%"
::get cirrent date
makecab /D RptFileName=~.rpt /D InfFileName=nul /f nul >nul
for /f "tokens=3-7" %%a in ('find /i "makecab"^<~.rpt') do (
set "year=%%e"
set "mon=%%b"
set "day=%%c"
)
del ~.*
popd
:: convert month to numeric string
for %%a in (
"Jan-01" "Feb-02" "Mar-03" "Apr-04" "May-05" "Jun-06" "Jul-07" "Aug-08" "Sep-09" "Oct-10" "Nov-11" "Dec-12"
) do (
for /f "tokens=1,2 delims=-" %%x in ("%%~a") do (
if "%mon%" equ "%%x" (
set "mon=%%y"
goto :skip
)
)
)
:skip
set "c_date=%year%%mon%%day%"
::echo %c_date%
:: is switch is for force overwriting
robocopy "%source%" "%dest%" * /maxage:1 /minage:%c_date% /is
robocopy is built-in every windows since Vista.If your are running under XP or Vista you'll need to download it from microsoft site.
This Batch file selects all files that were created on the same date before today. If you are sure that there are files created yesterday, then it solve your problem.
#echo off
setlocal EnableDelayedExpansion
set "yesterday="
for /F "skip=5 tokens=1,4*" %%a in ('dir /TC /O-D /A-D') do (
if "%%a" neq "%date%" (
if not defined yesterday set "yesterday=%%a"
if "%%a" equ "!yesterday!" (
echo Created yesterday: %%a "%%c"
) else (
goto break
)
)
)
:break

Batch Script - (Stop services, move log files to other directory, append date once move)

I'm a newbie in batch scripting. How can i add a currentdate on the filename once i move the files to other directory? Can you please check my code below? Thanks!
This is how it works:
-- I need to copy some files to other directory in order to kill the running processes which are (dsst)
-- once the dsst is not running, it should stop the GESWCPAServer and delete the copied files in c:temp
-- Next, copy the logfiles from C:\LOGFILES to C:\LOGFILES\Archive.
-- after the files has been copied. it will now start the services.
Thanks!
-------------------------------------------------------------------
#ECHO off
copy D:\fp_swenv\cg_fp\config\*.magik c:\temp
sc stop GESWCPAServer
:loop
echo checking for task list
tasklist /NH /FI "IMAGENAME eq dsst_writer_acp.exe" | find /I "dsst_writer_acp.exe"
rem tasklist /NH /FI "IMAGENAME eq textpad.exe" | find /I "textpad.exe"
if %ERRORLEVEL% == 0 goto sleeploop
goto finish_up
:sleeploop
echo Sleeping 10secs
sleep 10
goto loop
:finish_up
del c:\temp\*.magik
sc stop GESWDisptcher51
sc stop GESWCPAClient
sleep 10
set logpath1="C:\LOGFILES"
set arcpath1="C:\LOGFILES\Archive"
c:
cd %logpath1%
FORFILES /D -1 /M *.log /C "cmd /c move #path %arcpath1%"
cd /D %arcpath1%
sc start GESWCPAServer
sleep 10
echo checking for task list
tasklist /NH /FI "IMAGENAME eq dsst_writer_acp.exe" | find /I "dsst_writer_acp.exe"
rem tasklist /NH /FI "IMAGENAME eq textpad.exe" | find /I "textpad.exe"
if %ERRORLEVEL% == 1 goto sleeploop
sc start GESWDisptcher51
sc start GESWCPAClient
#ECHO ON
---------------------------------------------------------------------------
Please check if this works -
Replace your below code with my code.
set logpath1="C:\LOGFILES"
set arcpath1="C:\LOGFILES\Archive"
c:
cd %logpath1%
FORFILES /D -1 /M *.log /C "cmd /c move #path %arcpath1%"
My Code -
EDIT - Added the zip option as requested by OP in the comment.
#echo OFF
set logpath1=c:\Logfiles
set arcpath1=c:\Logfiles\archive
cd /d %logpath1%
for /f %%x in ('wmic os get localdatetime ^| findstr /b [0-9]') do set TS=%%x
set yyyy=%TS:~0,4%
set mm=%TS:~4,2%
set dd=%TS:~6,2%
set hh=%TS:~8,2%
set min=%TS:~10,2%
set timestamp=%dd%-%mm%-%yyyy%_%hh%-%min%
for /f %%i in ('dir /b *.log') do call :moveandrename "%%i"
goto :jump
:moveandrename
set filename=%~n1
set fileextn=%~x1
move /y %filename%%fileextn% %arcpath1%\%filename%-%timestamp%%fileextn% >nul 2>&1
goto :eof
:jump
cd %arcpath1%
C:\Program Files\WinZip\wzzip.exe -a Archive_%timestamp%.zip *.log
if not %errorlevel% EQU 0 echo.Zip operation failed on %timestamp% >>zipresult.txt & goto :eof
del *.log
:eof
Cheers, G

How to set variable with the result of findstr

I am trying to write a batch file which searches for pdf files and finds how many pages they have and loop all pages.
I wrote the following. I can find the files, I can even find the pagecounts with a tool named pdftk. The results is as below.
C:\Users\test\Documents\fishes\Fish_1.pdf
NumberOfPages: 5
How can I set a variable which has the value of 5?
#ECHO off
for /R %%i IN (*.pdf) DO (
ECHO %%i
"C:\Program Files (x86)\PDF Labs\PDFtk Server\bin\pdftk.exe" %%i dump_data | findstr NumberOfPages
set pagecount = findstr NumberOfPages ???
FOR /L %%j IN (1,1,%pagecount%) DO (
ECHO "page " + %%j
)
)
You were already 90% there. Use the FOR /F command to process the results of a command. Type HELP FOR from the command prompt for more info.
for /f "tokens=2" %%A in (
'"C:\Program Files (x86)\PDF Labs\PDFtk Server\bin\pdftk.exe" %%i dump_data ^| findstr NumberOfPages'
) do set numberOfPages=%%A