write-warning not writing to a file in catch

ITinNeed 1 Reputation point
2021-04-28T06:01:26.7+00:00

Im reading variables form a file and then trying to delete the folders. im trying to make some error handle to know if the files does not exist but the catch is not working when for example the path is not found

$values = Import-Clixml -Path C:\script\paths.clixml
foreach ($value in $values)
{
try
{
rm -r -fo $value
}

    Catch
        {
            Write-Warning " $($value) could not be deleted because $($_.Exception.Message)" 3>> C:\script\errors.txt
        }

}
Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
4,618 questions
No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Ian Xue (Shanghai Wicresoft Co., Ltd.) 18,351 Reputation points Microsoft Employee
    2021-04-28T09:59:29.143+00:00

    Hi,

    Try setting the ErrorAction to stop.

    $values = Import-Clixml -Path C:\script\paths.clixml  
    foreach ($value in $values)  
    {  
        try  
        {  
            rm -r -fo $value -ErrorAction Stop  
        }  
        Catch  
        {  
            Write-Warning " $($value) could not be deleted because $($_.Exception.Message)" 3>> C:\script\errors.txt  
        }  
    }  
    

    Best Regards,
    Ian Xue

    ============================================

    If the Answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    No comments