This the final part of the series. I’ll show the different functions that check several parameters so the script will run flawlessly.
The Init function
The name “Init” is a name I gave to the function becaue it’s the initial function that calls all the other functions.
The first part of the function look like this:
Function Init(){ $Error.Clear() # If the createconfig parameters is set If($createconfig -ne "") { Create-Config $createconfig exit 0 }
First all the errors are cleared so no messages from former executions will be in the logfile.
Second the script checks if the script is executed to create a config. If the parameter is set the “Create-Config” function is called.
The next part of the script checks if the parameter “config” is set.
# Check for the "config" parameter. If so load the file If($config -ne "") { # Does the file exist If((Check-Config $config) -eq 0) { $xmlconfig = [xml]( Get-Content $config) $source = $xmlconfig.Configuration.SourceImages $sourceorg = @() Foreach($s In $xmlconfig.Configuration.SourceReorganisation.Source) { $sourceorg = $sourceorg + $s } $destimage = $xmlconfig.Configuration.DestinationImage $destthumb = $xmlconfig.Configuration.DestinationThumb $destorg = @() Foreach($d In $xmlconfig.Configuration.DestinationReorganisation.Destination) { $destorg = $destorg + $d } $archive = $xmlconfig.Configuration.ImageArchive $sizeimage = $xmlconfig.Configuration.SizeImage $sizethumb = $xmlconfig.Configuration.SizeThumb $sourceext = $xmlconfig.Configuration.SourceExtension $targetext = $xmlconfig.Configuration.TargetExtension $logdir = $xmlconfig.Configuration.Logdirectory $cleanfolder = @() Foreach($c In $xmlconfig.Configuration.CleanFolder.Folder) { $cleanfolder = $cleanfolder + $c } } Else { exit 0 } }
It checks if the file exists. If it does it the file is loaded. If not the script is stopped. The config file is not mandatory for the script because it can work with only parameters.
The next part is to check all the values:
# Check values If((Check-Logdir $logdir) -ne 0){exit 0} If((Check-SourceExtension $sourceext) -ne 0){ exit 0 } If((Check-TargetExtension $targetext) -ne 0){ exit 0 } If((Check-Dimensions $sizeimage $sizethumb) -ne 0){ exit 0} If((Check-Directories $source) -ne 0){ exit 0} If((Check-Directories $destimage) -ne 0){ exit 0} If((Check-Directories $destthumb) -ne 0){ exit 0} If((Check-Directories $archive) -ne 0){ exit 0} If((Check-Directories $archive) -ne 0){ exit 0}
Function Check-Logdir
The code check if the logdir is given or exists. It look like this:
# Function Check-Logdir # This function checks the logdirectory # # Parameters: # [string] $strLogdir: Directory variable # Return: # [int] 0: Succes # [int] 1: Error Function Check-Logdir([string]$strLogdir) { #If no log directory is given If([string] $logdir -eq "") { $message = "No log directory is given" Write-Host $message Return 1 } #If the log directory does not exist If(!(Test-Path $strLogdir)) { $message = "The log directory $strLogdir does not exist!" Write-Logfile $message Write-Host $message Return 1 } Return 0 }
Function Check-SourceExtension
The code check for a source extension parameter. If no parameter is given it uses the standard source extension.
# Function Check-SourceExtension # This function checks the the given extension # # Parameters: # [string] $strExt: Extension the script searches for # Return: # [int] 0: Success # [int] 1: Error Function Check-SourceExtension([string]$strExt) { If([string] $strExt -eq "") { $message = "No source extension is given. Standard extension $SOURCEEXTENSION will be used." Write-Logfile $message Write-Host $message Return 0 } return 0 }
Function Check-TargetExtension
This function works the same as the function Source-Extension but sets a different value in case of an error.
# Function Check-SourceExtension # This function checks the the given extension # # Parameters: # [string] $strExt: Extension the script will convert the images to # Return: # [int] 0: Success # [int] 1: Error Function Check-TargetExtension([string]$strExt) { If([string] $strExt -eq "") { $message = "No target extension is given. Standard extension $TARGETEXTENSION will be used." Write-Logfile $message Write-Host $message Return 0 } return 0 }
Function Check-Dimensions
The following function checks if the dimensions given at the parameters are right.
# Function Check-Dimensions # This function checks the given dimensions voor the image resizing # # Parameters: # [int] $sizeimage: Size of large image # [int] $sizethumb: Size of thumbnail # Return: # [int] 0: Success # [int] 1: Error Function Check-Dimensions($sizeimg, $sizethb) { # If the size of the resize is greater than the original If($sizeimg -ne "" -and $sizeimg -lt $sizethb) { $message = "Size of the large image is greater than the thumbnail size." Write-Logfile $message Write-Host $message Return 1 } # If no parameter is given for the larger image If($sizeimg -eq "" -or 0) { $message = "No size given for the image." Write-Logfile $message Write-Host $message Return 1 } # If no parameter is given for the thimbnail image If($sizethb -eq "" -or 0) { $message = "No size is given or the thumbnail." Write-Logfile $message Write-Host $message Return 1 } return 0 }
Function Check-Directories
This function checks if a directory value is given or if it exists.
# Function Check-Directories # This function checks the directory is given or exists # doorgegeven variabele een waarde bevat # # Parameters: # [string] $strDir: Directory # Return: # [int] 0: Success # [int] 1: Error Function Check-Directories([string]$strDir) { #If no directory is given If([string] $strDir -eq "") { $message = "No directory given!" Write-Logfile $message Write-Host $message Return 1 } #If directory doesn't exist If(!(Test-Path $strDir)) { $message = "Directory $strDir doesn't exist!" Write-Logfile $message Write-Host $message Return 1 } Return 0 }
The next part is to get the image format of the target extension:
# Get the image format $imageFormat = Get-Imageformat $targetext
The code for getting the image format looks like this:
# Function Get-Imageformat # Get the image format based on the parameter # # Parameters: # [string] $strExt: String with extension # Return: # [string] $imageFormat: String with image format Function Get-Imageformat([string]$strExt) { $imageFormat = ""; # Controleer de extensie Switch($strExt) { # Set the extension "gif" {$imageFormat = "gif"} "GIF" {$imageFormat = "gif"} "jpg" {$imageFormat = "jpeg"} "jpeg" {$imageFormat = "jpeg"} "tiff" {$imageFormat = "tiff"} "TIFF" {$imageFormat = "tiff"} "png" {$imageFormat = "png"} "PNG" {$imageFormat = "png"} # If the given parameter does not ccontain a right image format default { $message = "The extension os no known image format!" Write-Logfile $message Write-Host $message exit 0 } } # Return the image format Return $imageFormat }
The next part is to get all the files and folders from the given directory.
# Get alle the files and directories $arraySourcedir = Get-Sourcedirs $source $sourceext The code to get all the files and folders looks like this: [cc lang="powershell"] # Function Get-Sourcedirs # This function returns all the subdirectories and files from the given source directory # # Parameters: # [string] $s # Resturns # [array] $y: Array with all subdirectories and files Function Get-Sourcedirs([string]$s, [string]$e) { # Execute the Get-Child-Item function $y = Get-ChildItem -r $s -include $e | % { $_.FullName } # Return results return $y }
The next part is to start converting the images
# If there any results in the sourcearray If($arraySourcedir.length -gt 0) { # Loop through the functions for image conversion Foreach($item In $arraySourcedir) { Convert-Image $item $destimage $sizeimage $targetext $imageFormat Convert-Image $item $destthumb $sizethumb $targetext $imageFormat Move-Image $item $archive } } Else { # Write error in logfile $message = "No images found in given directory!" Write-Host $message Write-Logfile $message } }
In this part of code another function is called named “Move-Image”. This function moves the original file to the given archive directory. The code looks like this:
# Function Move-Image # This function moves the original image. # It checks if the target directory exists. If not it creates the directory # # Parameters: # [string] $imageLocation: Original location of the image # [string] $to: Target location of the image Function Move-Image([string]$imageLocation, [string] $to) { # Create a new path for the file $newImageLocation = Replace-String $source $to $imageLocation # Get the directory from the path $newFolder = [System.IO.Path]::GetDirectoryName($newImageLocation) # Test if the target directory exists If(!(Test-Path $newFolder)) { # If not create it New-Item $newFolder -type directory } # Move the image Move-Item $imageLocation $newImageLocation -force }
The above code uses the function “Replace-String” that is also used in the function “Convert-Image”.
The last part of the code starts the reorganization and cleaning of the directory:
# Reorganize directories Reorganise-Folders $sourceorg $destorg # If the "cleanfolder" parameter is set If($cleanfolder) { If($cleanfolder.length -gt 0) { Clean-Folder $cleanfolder } }
The function for reorganizing the directory by selecting the first three characters from the image’s directory. Creating an new directory and move the images to the archive:
# Function Reorganise-Folders # This function reorganises the directories by selecting the first three characters # from the original directory. # Example: 1020567 will be replaced with 102 # # Parameters: # [array] $s: Source directory # [array] $d: Target directory Function Reorganise-Folders($s, $d) { # Check if the directories are correct and exist If($s.length -and $d.length -gt 0) { For($i = 0; $i -lt $s.length; $i++) { If((Check-Directories $s[$i]) -ne 0){ exit 0} If((Check-Directories $d[$i]) -ne 0){ exit 0} # Get alle directories $arraySourcedirs = Get-ChildItem $s[$i] | Where { $_.attributes -eq "Directory" } # Loop through the array If($arraySourcedirs.length -gt 0) { Foreach($item in $arraySourcedirs) { # Convert the item in the array to string [string] $dir = $item # Check if the length of the directory is no greater than 3 If($dir.length -gt 3) { # Create the new name $newName = $dir.Substring(0,3); # Create the old en new full paths $oldDir = $s[$i] + "\" + $dir $newDir = $d[$i] + "\" + $newName + "\" + $dir # Test if the new path exists If(!(Test-Path $newDir)) { # If not create it New-Item $newDir -type directory } # Move the images from the directory to the new one #Move-Item $oldDir $newDir -force -verbose Write-Host "robocopy.exe $olddir $newdir /E /S /R:10 /MOVE" robocopy.exe $olddir $newdir /E /R:10 /MOVE /IS } } } } }
An example for an archive folder would be:
- C:\Imageconversion\Archive\104\10453678\
Where the original directory would be:
- C:\Imageconversion\Source\10453678\
The last function cleans all the folder given. The original images are moved away from the source directory what leaves empty directories. To clean them the following function is used:
# Function Clean-Folders # This function makes it possible to clean up the empty directories # # Parameters: # [array] $folder: Location of the folder that need to be cleaned Function Clean-Folder($folder) { Foreach($i In $folder) { # Get all the subdirectories $f = Get-ChildItem $i | Where-Object {$_.PSIsContainer -eq $True} # Check the length of the results If($f.length -gt 0) { # Loop door de items heen Foreach ($item in $f) { # Check if the directory doesn't contain any files If($item.GetFiles().Count -eq 0) { # Create path to dir $d = $i + "\" + $item # Check if the path still exists If(Test-Path $d) { # Remove dir Remove-Item $d -Recurse } } } } } }
I hope you enjoyed the article. It contained a lot functionality what created the solution. If you have any recommendation or remarks about the article leave a comment.
The full script can be downloaded from here.