Exceptions in Try

Hi people, need some help with a script I build

$username = "user"
$password = "pass" | ConvertTo-SecureString -asPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential($username, $password)

Connect-PowerBIServiceAccount -Credential $credential

$filePath = "c:/tmp/workspaces.txt"

$lines = Get-Content -Path $filePath

$Reports =
foreach ($line in $lines) {
    Try {
        $workspaceId = [Guid]($line.Trim())
        Get-PowerBIDashboard -WorkspaceId $workspaceId
    } catch {
        if ($_.Exception.Message -like "*Unauthorized*") {
            Write-Host "No se pudo obtener el panel del espacio de trabajo con ID '$workspaceId'."
        } else {
            $_
        }
    }
}

$Reports | Export-Csv -Path "c:/tmp/Tableros.csv" -NoTypeInformation

and in some cases I give this error:

Get-PowerBIDashboard : Operation returned an invalid status code 'Unauthorized'
En C:\tmp\reportes.ps1: 16 Carácter: 9
+         Get-PowerBIDashboard -WorkspaceId $workspaceId
+         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : WriteError: (Microsoft.Power...owerBIDashboard:GetPowerBIDashboard) [Get-PowerBIDashboard], Htt  
   pOperationException
    + FullyQualifiedErrorId : Operation returned an invalid status code 'Unauthorized',Microsoft.PowerBI.Commands.Reports.Get  
   PowerBIDashboard

What i need is catch the error and change the error message, I tried many things but nothing works.

Any ideas?

Thanks!

Without proper formatting of your code, it is hard to really tell your issue. However, I dont see the following at the beginning of your script:

$ErrorActionPreference = 'Stop'

I also see the following (could be due to improper formatting of your post):

$.Exception.Message

Which should be:

$_.Exception.Message

Sorry tonyd, i’m new here.

Format corrected.

And you tried adding the following to the beginning of your script?

$ErrorActionPreference = 'Stop'

Nope, i didn’t… The idea is the script doesn’t stop when recieves an error, I need to print a message for each error.

Please try adding that to the beginning of your script.

$ErrorActionPreference

Determines how PowerShell responds to a non-terminating error, an error that doesn’t stop the cmdlet processing. For example, at the command line or in a script, cmdlet, or provider, such as the errors generated by the Write-Error cmdlet.

You are the best!

It’s worked!

Thanks a lot my friend!