it took me a long time to figure this out so i just tought it might be usefull for someone.
If you need to set up a hotfolder, or a bunch of them in this case and convert all images that are droped in said hotfolder to another one, this script will work perfectly...
Code: Select all
#parameters for the script
$BaseDir = "e:\hotfolder\raiz" #Define here the root folder of your files tree
$nconvertpath = "E:\Hotfolder\nconvert\nconvert" #define here were nconvert is installed
$logfile = "e:\hotfolder\log.txt" #define were you wanna store a log of the watchfolder interactions
$NameToFind = "input" #define here name of the folders inside the tree you want to become Hotfolders
#end of parameters
#finds the path for every folder inside the tree that are $nametofind
$dirs = Get-ChildItem $BaseDir -Recurse | Where-Object { $_.PSIsContainer -and $_.Name.EndsWith($NameToFind)}
#displays the folders that it found
write-host "The following folders will become hotfolders"
$dirs.fullname
#starts up the array for the watchfolders
$FSWatchers = @($dirs.fullname | ? { Test-Path -Path $_ } | % {new-object System.IO.FileSystemWatcher})
### DEFINE ACTIONS AFTER AN EVENT IS DETECTED
$Action = { Write-Host "DOING ACTION"
$path = $Event.SourceEventArgs.FullPath #get's the path of the $nametofind where the file was created
$changeType = $Event.SourceEventArgs.ChangeType #gets the type of alteration it was made in this case "create" because i only trigger on it is creating a new file
$logline = "$(Get-Date), $path, $changeType" #defines a log line can be removed if you dont want logs
Add-content $logfile -value $logline #writes to logfile
#specific string handling because my action is using nconvert and it doesn't work well with filename with spaces without cotations
#also please note that i use a diferent output folder named output at the same level of the input folder so i need to juggle here some regex
$filename = [System.IO.Path]::GetFileName($path)
$filenameWithoutSpaces = $filename -replace '\s', ''
$outpath = ($path -replace '\\[^\\]+\\[^\\]+$','')+"\output\$filenameWithoutSpaces"
$outpath
#the command to convert with nconvert
cmd.exe /c "E:\Hotfolder\nconvert\nconvert -D -Quiet -out jpeg -dpi 300 -o $outpath `"$path`"" #Xnconvert command.
}
foreach ($dir in $dirs.fullname){
### SET FOLDER TO WATCH + FILES TO WATCH + SUBFOLDERS YES/NO
$watcher = New-Object System.IO.FileSystemWatcher; #create the filesystem watcher that makes it hotfolders
$watcher.path= "$dir\" #watchfolder path is assigned
$watcher.Filter = "*.*" #search for all type of files crested
$watcher.IncludeSubdirectories = $true #not needed but i set it anyway usefull if you drop subfolders inside the input folders (however is not handled in the command call so mighty be buggy)
$watcher.EnableRaisingEvents = $true #not needed but i set it anyway
Register-ObjectEvent $watcher "Created" -Action $Action; ### DECIDE WHICH EVENTS SHOULD BE WATCHED in this case create event
}
while ($true) {sleep 5} #loop