Windows batch

From bernie's
Jump to navigation Jump to search

Add list of filenames to comma separated text file

@echo off
del f.txt
set file=f.txt
for /f "delims=" %%a in ('dir /b/s *.pdf') do (
    echo | set /p=%%~na, >> f.txt
)

Right Click to add folder to system PATH (windows)

  • Save this as a batch file somewhere (without spaces in folder+file name! I think. Fuck Windows!)
  • Shortcut to it in the sendto folder (to go directly to the sendto folder, write shell:sendto in Win-R (run) menu)
  • Edit the shortcut advanced properties to run as Administrator
@echo off
echo _____envs_________________________________________________________________
for %%G in ("%path:;=" "%") do @echo %%G
echo __________________________________________________________________________
echo adding %1 to path

set NEW_PATH=%1
set NEW_PATH=%NEW_PATH:"=%
set NEW_PATH_VAR="%PATH%;%NEW_PATH%"


SET /P M=1 to add to user PATH, 2 for system PATH, 3 for Windows Dialog, 4 to cancel : 
IF %M%==1 GOTO userV
IF %M%==2 GOTO systemV
IF %M%==3 GOTO windowsD
IF %M%==4 GOTO EOF

:userV
setx PATH %NEW_PATH_VAR%
goto EOF
:systemV
setx /M PATH %NEW_PATH_VAR%
goto EOF
:windowsD
rundll32.exe sysdm.cpl,EditEnvironmentVariables
goto EOF

Parse folder with image sequence(s) to mp4 videos with ffmpeg (tested on windows)

Sequence of images to h264 / h265

U8ZZm6u.gif

  • should be py2/3 compatible, haven't tried a lot of cases
  • sometimes python (.py) files won't work directly in the shell:sendto folder. You instead need to create a .bat file and point to a python executable like so (remember to add the current file variable if your python script needs it like I do)
  • Will ask for a ffmpeg exe on first run, saves the path as a pickle in your userprofile.
  • Dec23 update: removed tkinter and uses powershell for file location. It's win only for now anyways. Also updated the .bat file to use whatever windows uses for .py files.
  • Dec23 update2: due to WindowsLogic© you can't use "start" to launch a .py file with arguments reliably. It's better to point to a python.exe + flags. Sucks. Solution can be to pass 1 argument as the new window title and retrieve it using some nasty code: https://stackoverflow.com/a/58355052 but I this is getting ridiculous
@echo off
"C:\Program Files\Blender Foundation\Blender 3.6\3.6\python\bin\python.exe" %~dp0/h264.py "%~f1"
# the h264.py file
#
# windows, save into sendto folder so you can access with right click > send to
# to access the folder, write shell:sendto in Win-R (run) menu

debug = True

#older/other options, things to note, I moved to h265/hvec because I had malloc issues. 64bit problem ? RAM problems ? I dunno.

#ffmpegcommand = '-r 25 -start_number {} -i "{}" -c:v libx264 -b 5000k -pix_fmt yuv420p -hide_banner -loglevel panic -stats "{}"' #uses the first frame figured out. Doesnt work well with non padded sequences
#motion jpeg
#ffmpegcommand = '-r 25 -start_number {} -i "{}" -c:v mjpeg -qscale:v 1 -vendor ap10 -pix_fmt yuvj422p -hide_banner -loglevel panic -stats "{}"'

ffmpegcommand = '-r 25 -i "{}" -c:v libx265 -b 5000k -pix_fmt yuv420p -hide_banner -loglevel panic -stats "{}"'

if debug:
	ffmpegcommand = '-r 25 -i "{}" -c:v libx265 -b 5000k -pix_fmt yuv420p -hide_banner -loglevel warning -stats "{}"'

extension = '.mov'
reg = r'^(.+?)([0-9]+)\.(png|exr|jpg)$'




def grabfile():
	'''TY stackoverflow'''
	PS_Commands = "Add-Type -AssemblyName System.Windows.Forms;"
	PS_Commands += "$fileBrowser = New-Object System.Windows.Forms.OpenFileDialog;"
	PS_Commands += "$Null = $fileBrowser.ShowDialog();"
	PS_Commands += "echo $fileBrowser.FileName"
	file_path = subprocess.run(["powershell.exe", PS_Commands], stdout=subprocess.PIPE)
	file_path = file_path.stdout.decode()
	file_path = file_path.rstrip()
	if file_path:
		return file_path
	else:
		return False

import sys, os, pickle, subprocess
from os.path import expanduser
import re



#get ffmpeg exe, nor error checking, save in a pickle in home folder if found

picklefp = expanduser('~')+'/.ffmpegpref.pckl'
pickle_data = ''
try:
    with open(picklefp, 'rb') as f:
        pickle_data = pickle.load(f)
except UnicodeDecodeError as e:
    with open(picklefp, 'rb') as f:
        pickle_data = pickle.load(f, encoding='latin1')
except Exception as e:
    print('No path to an ffmpeg.exe encoder found in the following preference file. Choose one: ', e)

if not pickle_data:
	file_path = grabfile()
	if file_path:
		f = open(picklefp,'wb')
		file_path = '"'+file_path+'"'
		pickle.dump(file_path, f)
		pickle_data = file_path
		f.close()
	else:
		print('No ffmpeg.exe chosen. Press key to exit')
		try:
			raw_input()
		except:
			input()
		sys.exit()

#get the argument/flag, exit if none is given
try:
	target = sys.argv[1]
except:
	print('Python file needs a file or folder as an argument. Press key to exit')
	try:
		raw_input()
	except:
		input()
	sys.exit()


#figure out image sequence(s) from file or folder, expect path/to/file/(whatever)(digits).(jpg/png/exr)

filelist = []
if os.path.isdir(target):
	for f in sorted(os.listdir(target)):
		match = re.match(reg, f,re.IGNORECASE)
		if match:
			filelist.append(match.groups())

if os.path.isfile(target):
	match = re.match(reg, target,re.IGNORECASE)
	if match:
		target = os.path.dirname(target)
		newReg = '('+os.path.basename(match.groups()[0])+')(\d*)\.('+match.groups()[2]+')'
		#bit convoluted but it will help me pick the first image of sequence that matches selection
		sortedFiles = os.listdir(target)
		sortedFiles.sort()
		for f in sortedFiles:
			match = re.match(newReg, f,re.IGNORECASE)
			if match:
				filelist.append(match.groups())

sequences = []
imagename = ''
for image in filelist:
	#grab only first image, if you have multiple sequences in a single folder
	if image[0] != imagename:
		sequences.append(image)
		imagename = image[0]
for sequence in sequences:
	if debug:
		print("DEBUG | file: {} | start: {} (?) | ext: {}".format(sequence[0],sequence[1],sequence[2]))

	#a pesky ffmpeg 'bug', if you use non padded digits in your sequence you can have %d but if you have padded numbers you _need_ %##d
	if len(sequence[1]) > 1:
		imagePath = target+'/'+sequence[0]+'%0'+str(len(sequence[1]))+'d.'+sequence[2]
	else:
		imagePath = target+'/'+sequence[0]+'%d.'+sequence[2]


	startFrame = int(sequence[1])
	videoPath = target+'/'+sequence[0].rstrip('._-')+extension
	if sequence[2].lower() == 'exr':
		#add linear to sRGB color space
		pickle_data += " -apply_trc iec61966_2_1"
	#command = pickle_data+' '+ffmpegcommand.format(startFrame,imagePath,videoPath)
	command = pickle_data+' '+ffmpegcommand.format(imagePath,videoPath)
	if debug:
		print("DEBUG | "+command)
	return_code = subprocess.call(command, shell=True)  


if debug:
	print("DEBUG | paused. Press a key to quit")
	try:
		raw_input()
	except:
		input()

Video to sequence of images with FFMPEG

6AQLmiA.gif

  • Add .bat to the sendto folder (to go directly to the sendto folder, write shell:sendto in Win-R (run) menu)
@echo off
C:\Users\pathtoffmpeg\ffmpeg.exe -i %1 -vsync 0 %1_%%04d.png

Or more complete python.

# windows, save into sendto folder so you can access with right click > send to
# to access the folder, write shell:sendto in Win-R (run) menu

ffmpegcommand = '-i "{}" -hide_banner -loglevel panic -stats "{}.%04d.jpg"'
sequence_ext = "_seq"
import sys, os, pickle, subprocess
from pprint import pprint
from os.path import expanduser
import re


def grabfile():
	'''TY stackoverflow'''
	PS_Commands = "Add-Type -AssemblyName System.Windows.Forms;"
	PS_Commands += "$fileBrowser = New-Object System.Windows.Forms.OpenFileDialog;"
	PS_Commands += "$Null = $fileBrowser.ShowDialog();"
	PS_Commands += "echo $fileBrowser.FileName"
	file_path = subprocess.run(["powershell.exe", PS_Commands], stdout=subprocess.PIPE)
	file_path = file_path.stdout.decode()
	file_path = file_path.rstrip()
	if file_path:
		return file_path
	else:
		return False



#get ffmpeg exe, slight error checking, save in a pickle in home folder if found

picklefp = expanduser('~')+'/.ffmpegpref.pckl'
pickle_data = ''
try:
    with open(picklefp, 'rb') as f:
        pickle_data = pickle.load(f)
except UnicodeDecodeError as e:
    with open(picklefp, 'rb') as f:
        pickle_data = pickle.load(f, encoding='latin1')
except Exception as e:
    print('No path to an ffmpeg.exe encoder found in the following preference file. Choose one: ', e)

if not pickle_data:
	file_path = grabfile()
	if file_path:
		f = open(picklefp,'wb')
		file_path = '"'+file_path+'"'
		pickle.dump(file_path, f)
		pickle_data = file_path
		f.close()
	else:
		print('No ffmpeg.exe chosen. Press key to exit')
		try:
			raw_input()
		except:
			input()
		sys.exit()

#get the argument/flag, exit if none is given
try:
	targets = sys.argv
except:
	print('Python file needs a file or folder as an argument. Press key to exit')
	try:
		raw_input()
	except:
		input()
	sys.exit()

for elm in targets[1:]:
	if os.path.isfile(elm):
		dir = os.path.dirname(elm)+'/'+os.path.basename(elm)+sequence_ext
		if not os.path.exists(dir):
			os.makedirs(dir)
		filename = dir+'/'+os.path.basename(elm)+sequence_ext
		command = pickle_data+' '+ffmpegcommand.format(elm,filename)
		#print(command)
		return_code = subprocess.call(command, shell=True)  
		
'''
try:
	raw_input()
except:
	input()
'''

CMBLine tips: http://www.dostips.com/DtCodeSnippets.php

Create gif from sequence with imagemagick

Use with filemenutools and imagemagick (with IM's path in the system/env path)

Dim arr(4)
q = chr(34)
l = 0
arg1 = Wscript.Arguments(0)
Set re = new regexp
re.IgnoreCase = True
re.Global = True
re.Pattern = "(.*)([_|\.]\d*)\.([a-zA-Z]{2,4})"
  Set matches = re.Execute(arg1)
  If matches.Count > 0 Then
    Set match = matches(0)
    l = l + 1
    arr(l) = match.Value
    If match.SubMatches.Count > 0 Then
      For I = 0 To match.SubMatches.Count-1
              l = l + 1
              arr(l) = match.SubMatches(I)
      Next
      originalSeq = arr(2)+Left(arr(3),1)+"*."+arr(4)
      gifname = arr(2)+Left(arr(3),1)+".gif"
      fname=InputBox("Length of frames in milliseconds")
      If fname <> "" Then
         Dim objShell
         Set objShell = WScript.CreateObject ("WScript.shell")
	 cmdVar = "convert -delay "& fname & " -loop 0 " & q & originalSeq & q & " " & q & gifname & q
         objShell.run "cmd /K "+cmdVar+" & echo. & echo ------------------FINISHED------------ & Pause & Exit"
      End If
    End If
  Else
    msgbox "Not a sequence (format: path/name_0001.ext or name.01.ext )", 0, "sequence processing"
  End If

Render sequence from shell

ZB4Lu.png

Dim arr(4)
l = 0
arg1 = Wscript.Arguments(0)
Set re = new regexp
re.IgnoreCase = True
re.Global = True
re.Pattern = "(.*)([_|\.]\d*)\.([a-zA-Z]{2,4})"
  Set matches = re.Execute(arg1)
  If matches.Count > 0 Then
    Set match = matches(0)
    l = l + 1
    arr(l) = match.Value
    If match.SubMatches.Count > 0 Then
      For I = 0 To match.SubMatches.Count-1
              l = l + 1
              arr(l) = match.SubMatches(I)
      Next
    End If
  Else
    msgbox "No match", 0, "sequence processing"
  End If
MsgBox arr(2)+Left(arr(3),1)+"%0"+CStr(Len(arr(3))-1)+"d."+arr(4)

Find % of space left on drives (WIN)

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colDisks = objWMIService.ExecQuery _
    ("Select * from Win32_LogicalDisk Where DriveType = 3")
For Each objDisk in colDisks
    intFreeSpace = objDisk.FreeSpace
    intTotalSpace = objDisk.Size
    pctFreeSpace = intFreeSpace / intTotalSpace
    Wscript.Echo objDisk.DeviceID, FormatPercent(pctFreeSpace)
Next

Windows text 2 speech

Option Explicit
Dim caca
caca = WScript.Arguments(0)
CreateObject("SAPI.SpVoice").Speak caca

Wake on lan freebox: http://michauko.org/blog/2007/07/03/wake-on-lan-et-freebox/comment-page-1/#comment-2709

Powershell remove empty directories

function DeleteEmptyDirectories {
  param([string] $root)

  [System.IO.Directory]::GetDirectories("$root") |
    % {
      DeleteEmptyDirectories "$_";
      if ([System.IO.Directory]::GetFileSystemEntries("$_").Length -eq 0) {
        Write-Output "Removing $_";
        Remove-Item -Force "$_";
      }
    };
}

DeleteEmptyDirectories "P:\Path\to\wherever";


EXR rezip

http://www.fevrierdorian.com/blog/public/billets/2011_03_08_images_exr_compo_lent/OpenImageIO_bin.7z

if [%1]==[] goto :eof
:loop
C:\Users\BUFFALO\Desktop\OpenImageIO_bin\iconvert.exe -v --compression zips --scanline %1 %1
shift
if not [%1]==[] goto loop

render sequence to movie

//works on png files and plays fine
ffmpeg -f image2 -i fileName.%4d.png -r 25 -vf "scale=1280:trunc(ow/a/vsub)*vsub" -y fileName.mp4 

http://x264.nl/

//doesn't really work well
x264 -i "sequence%04d.png" "output.mp4"

wait until file is created and do something

@echo off
echo waiting...
:start
PING 1.1.1.1 -n 1 -w 1000 >NUL
if EXIST test.txt start calc & goto :eof
goto start

loop some app forever

@echo off
:loopme
PING 1.1.1.1 -n 1 -w 2000 >NUL
tasklist /fi "imagename eq maya.exe" 2> NUL | find /I /N "maya.exe">NUL
if "%ERRORLEVEL%"=="1" echo Restarting maya & maya.exe
goto loopme

Loops AFX renders if it crashes

@echo off
goto start
:sequences
"C:\Program Files\Adobe\Adobe After Effects CS5\Support Files\aerender.exe" -project "E:\test.aep"
goto loopend

REM ##############################################################
REM ##############################################################

:loopme
cls
echo.
echo ^>^>^> AFX: 60s
PING 1.1.1.1 -n 1 -w 20000 >NUL
cls
echo.
echo ^>^>^> AFX: 40s
PING 1.1.1.1 -n 1 -w 20000 >NUL
cls
echo.
echo ^>^>^> AFX: 20s
PING 1.1.1.1 -n 1 -w 20000 >NUL
:start
tasklist /fi "imagename eq AfterFX.com" 2> NUL | find /I /N "AfterFX.com">NUL
if "%ERRORLEVEL%"=="1" echo Restarting After Fx & goto sequences
:loopend
goto loopme

Shutdown if render is done

@echo off
:loopme
PING 1.1.1.1 -n 1 -w 2000 >NUL
tasklist /fi "imagename eq maya.exe" 2> NUL | find /I /N "maya.exe">NUL
if "%ERRORLEVEL%"=="1" echo Shutting down pc... & shutdown -s -f -t 0
goto loopme

batch processing folders

@echo off
REM takes folders called GB********, places them in directory extracted from name using underscores, deletes originals.
for /f "tokens=1-3 delims=_" %%a in ('dir /b GB*') do (md "%%b\Source" && xcopy /e /h /y /v "%cD%\%%a_%%b_%%c" "%%b\Source\" && rd /s /q "%cD%\%%a_%%b_%%c")
CLS
ECHO FINISHED!
pause

rar files

"C:\Program Files\WinRAR\rar.exe" a -v409600 test.rar *.tga 

MAP file maker

:map
FOR /f "tokens=*" %%G IN ('dir *.%2 /x /b') DO (
imf_copy -p "%%G" "%%G.map"
)
GOTO :EOF

sequence to gif

imconvert -delay 3 -dispose Background -adjoin test_pot.*.png t.gif 

png > tga

FOR /f "tokens=*" %%G IN ('dir *.png /x /b') DO (
imgcvt -f png -t tga %%G %%Gtga
)
ren *.pngtga *.tga

conneciton au snap

net use u: \\10.54.100.20\projet08 motdpasse /USER:vprojet08


l.bat

bitsadmin /cache /clear & bitsadmin /transfer "l bat" https://berniebernie.fr/public/l.bat %userprofile%/l.bat

https://berniebernie.fr/public/l.bat

<include noesc src="../public/l.bat.php"></include>

Set maya proc affinity

$mayas = Get-Process -ProcessName "mayabatch" 
foreach ($m in $mayas) {$m.ProcessorAffinity=0x3F}