0

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.

Shreya Patil
  • 3
  • 1
  • 2
  • 1
    You also need to add `-ErrorAction Stop` to `Get-ChildItem`. – stackprotector Jul 03 '23 at 08:17
  • In short: `try` / `catch` only acts on _terminating_ errors, whereas it is far more typical for cmdlets to report _non-terminating_ errors. For the `catch` block to get invoked, non-terminating errors must be promoted to terminating ones by passing `-ErrorAction Stop` or by setting `$ErrorActionPreference = 'Stop'` beforehand. See the linked duplicate for more information. – mklement0 Jul 03 '23 at 13:22

0 Answers0