Saturday, April 26, 2014

PowerShell example to monitor files and directories for any changes using FileSystemWatcher

<# Create delegates that will be used when a file is altered and when when it is renamed #>
$updated = { Write-Host "File: " $EventArgs.FullPath " " $EventArgs.ChangeType ;$global:UpdateEvent = $EventArgs}

$Renamed = { Write-Host "File: " $EventArgs.OldFullPath " renamed to "$EventArgs.FullPath ; $global:RenameEvent = $EventArgs}



<# Create a fileWatcher that will monitor the directory and add its attributes#>
$fileWatcher = new-object System.IO.FileSystemWatcher
$fileWatcher.Path = "C:\Junk"
$fileWatcher.Filter = "*.txt";
$fileWatcher.IncludeSubdirectories = $true
$fileWatcher.NotifyFilter = [System.IO.NotifyFilters]::LastAccess `                      
                            [System.IO.NotifyFilters]::LastWrite, `
                            [System.IO.NotifyFilters]::FileName `
                            [System.IO.NotifyFilters]::DirectoryName

<# If a delegate has already been added to the FileWatchers for that event remove it and add the new one. #>
if($ChangedEvent) {$ChangedEvent.Dispose()}
$ChangedEvent = Register-ObjectEvent $fileWatcher "Changed" -Action $updated

if($CreatedEvent) {$CreatedEvent.Dispose()}
$CreatedEvent = Register-ObjectEvent $fileWatcher "Created" -Action $updated

if($DeletedEvent) {$DeletedEvent.Dispose()}
$DeletedEvent = Register-ObjectEvent $fileWatcher "Deleted" -Action $updated

if($RenamedEvent) {$RenamedEvent.Dispose()}
$RenamedEvent = Register-ObjectEvent $fileWatcher "Renamed" -Action $Renamed

$fileWatcher.EnableRaisingEvents = $true

<#
#To stop monitoring the text files in your specified directory run the script bellow.
if($RenamedEvent) {$RenamedEvent.Dispose()}
if($DeletedEvent) {$DeletedEvent.Dispose()}
if($CreatedEvent) {$CreatedEvent.Dispose()}
if($ChangedEvent) {$ChangedEvent.Dispose()}
#>

<#
     c# style go add delegates to your filewatcher
     fileWatcher.Changed += new FileSystemEventHandler(Wathcer_Changed);
     fileWatcher.Created += new FileSystemEventHandler(Wathcer_Changed); 
     fileWatcher.Deleted += new FileSystemEventHandler(Wathcer_Changed);

     static void Wathcer_Changed(object sender, FileSystemEventArgs e)
     {
          Console.WriteLine("Change Type = {0}, Path = {1}", e.ChangeType, e.FullPath);
     }
#>

PowerShell function to Update an Image or create a new image from an existing one

#This function can be used to change the color of an image or to cut out a part of an image.
#This can be used to clear pictures up for OCR'ing.
#Here are some example calls

# This example changes any pixel with more than 170 parts of blue to white.
#Update-ImageColor -CurrentFileName "c:\pic.jpg" -NewFileName "c:\PicNoBlue.jpg" -MaxBlue 170 -newColor $([System.Drawing.Color]::White)
#This function displays color in each pixel to help define the above statements parameters. 
#http://programmingthisandthat.blogspot.ca/2014/04/powershell-function-to-display-rgb.html 

# This example changes any pixel with more than 170 parts of blue to white.

#Update-ImageColor -CurrentFileName "c:\pic.jpg" -NewFileName "c:\small.jpg" -WidthStartPosition 100 -Width 100 -height 100 -heighttartPosition 100

Function Update-ImageColor{
[CmdletBinding()]
Param( [Parameter(Mandatory=$True,Position=1)] [string]$CurrentFileName,
[Parameter(Mandatory=$True,Position=1)] [string]$NewFileName,
[System.Drawing.Color]$newColor = [System.Drawing.Color]::Black,
[int]$MinCombined = -1,
[int]$MaxCombined = 800,
[int]$MaxRed = 400,
[int]$MaxGreen = 400,
[int]$MaxBlue = 400,
[int]$MinRed = -1,
[int]$MinGreen = -1,
[int]$MinBlue = -1,
[int]$Width=0,
[int]$height=0,
[int]$WidthStartPosition=0,
[int]$heighttartPosition=0,
[int]$ZoomFactor=1)
try {
$scrBitmap = [System.Drawing.Bitmap]($CurrentFileName)
$ActualColor = New-Object System.Drawing.Color
#make an empty bitmap the same size as scrBitmap
if($Width -eq 0){$Width = $scrBitmap.Width}
if($height -eq 0){$height = $scrBitmap.Height}
$newBitmap = new-object System.Drawing.Bitmap $Width, $height
for ($i = 0; $i -lt $newBitmap.Width; $i++) {
for ($j = 0; $j -lt $newBitmap.Height; $j++) {
#get the pixel from the scrBitmap image
$actulaColor = $scrBitmap.GetPixel($i+$WidthStartPosition, $j+$heighttartPosition);
if(($actulaColor.R -gt $MaxRed -or $actulaColor.R -lt $MinRed) -or
($actulaColor.G -gt $MaxGreen -or $actulaColor.G -lt $MinGreen) -or
($actulaColor.B -gt $MaxBlue -or $actulaColor.B -lt $MinBlue) -or
($actulaColor.R + $actulaColor.G + $actulaColor.B) -lt $MinCombined -or
($actulaColor.R + $actulaColor.G + $actulaColor.B) -gt $MaxCombined){

     $newBitmap.SetPixel($i, $j, $newColor)
}
else {

$newBitmap.SetPixel($i, $j, $actulaColor)
}

}

}
Remove-Item $NewFileName -Force -ErrorAction SilentlyContinue
#Size newSize = new Size((int)(originalBitmap.Width * zoomFactor), (int)(originalBitmap.Height * zoomFactor));
#Bitmap bmp = new Bitmap(originalBitmap, newSize);
$newBitmap.Save($NewFileName,[System.Drawing.Imaging.ImageFormat]::Jpeg)
$newBitmap.Dispose()
$scrBitmap.Dispose()
return "$NewFileName : Conversion Complete."


}
catch [Net.WebException] {
return $_.Exception

}

}