Problem: Powershell script should stops if an exception is caught by the try block for Get-ChildItem
command
$no_month = (Get-Date).AddMonths(-3)
$tcount = (Get-ChildItem -Path "E:" | Measure-Object).Count
# Count of total number of files that will be deleted
$count = ( Get-ChildItem -Include ".mp3" -Path "E:" -Recurse | Where-Object {($_.LastWriteTime -lt $no_month)} | Measure-Object).Count
If ($count -gt 0){
Try {
# Deleted the files older than 6 months
Get-ChildItem -Include ".mp3" -Path "E:" -Recurse | Where-Object {($_.LastWriteTime -lt $no_month)} -ErrorAction STOP
Get-ChildItem -Include ".mp3" -Path "E:" -Recurse | Where-Object {($_.LastWriteTime -lt $no_month)} | Remove-Item -ErrorAction STOP
#Call the function to Log messages
Log-Message "The total number of files present in the folder are: $tcount."
Log-Message "The number of files that will be deleted are: $count."
Log-Message "The number of files deleted are: $count."
}
Catch {
# Throws exception if any error occurs
Write-host -f Red "Error:" $_.Exception.Message
}
}else{
Log-Message "There are no files to be deleted."
}
I tried following ways:
Get-ChildItem -Include $file_extn -Path $deletion_path -Recurse | Where-Object {($_.LastWriteTime -lt $no_month)} -ErrorVariable Err -ErrorAction STOP if ($Err){write-host $Err -Foregroundcolor Red}
Get-ChildItem -Include ".mp3" -Path "E:" -Recurse | Where-Object {($_.LastWriteTime -lt $no_month)} -ErrorAction STOP
but the output I got is: Message: 'The total number of files present in the folder are: 167.' Has been Logged to File: logfile-2023-07-03_12-06-41.log Message: 'The number of files that will be deleted are: 41.' Has been Logged to File: logfile-2023-07-03_12-06-41.log Message: 'The number of files deleted are: 41.' Has been Logged to File: logfile-2023-07-03_12-06-41.log
But in above code if any of the Get-ChildItem
command runs into some error while execution it should stop the code and throw error. The Log-Message
function should not run.