0

I'm running a Powershell script from a Powershell window.
Inside this script, I'm trying to connect to a service, and wish to stop the script if the connection fails on an exception.
I'm catching the exception but the script refuses to stop, but continues on.
I tried checking error output using **-ErrorAction** and **-ErrorVariable** and many other things. But the issue is the script does not stop. The script is saved in a .ps1 file and I just run it from the shell windoe".\script.ps1"
Here's the code:
Write-Host "Attaching to cluster and retrieving credential" -ForegroundColor Gray
if ([string]::IsNullOrEmpty($clusterrg) -or [string]::IsNullOrEmpty($clustername)) {
    Write-Host "Failed to attacth to cluster. Parameters missing." -ForegroundColor  Red
    Write-Host "Use -clusterreg CLUSTER_RESOURCE_GROUP -clustername CLUSTER_NAME in the command line`n" -ForegroundColor Red
    Exit 1
} else {
    try{
        az aks get-credentials --resource-group $clusterrg --name $clustername
        Write-Host "Done`n" -ForegroundColor Green
    } catch {
        Write-Error $Error[0]
        exit 1
    }
}

Would appreciate any help.

Thanks you!

4
  • where is it supposed to stop? does break make any difference? Commented Feb 6, 2023 at 1:32
  • 1
    You are using the Azure CLI, not the Azure PowerShell commands. So try/catch as well as -ErrorAction and -ErrorVariable are not supported. You have to check the $LASTEXITCODE variable for errors. Commented Feb 6, 2023 at 12:35
  • @AbrahamZinala - if this fails, i need it to exit out of the script completely, as there is no reason to continue without the successful completion of this code. Thanks! Commented Feb 6, 2023 at 14:09
  • @zett42 - thank you. this is exactly what i needed. wish you wrote it as an answer, so i could upvote it. Thanks! Commented Feb 6, 2023 at 16:04

1 Answer 1

0

You are using the Azure CLI, not the Azure PowerShell commands. So try/catch as well as the common parameters -ErrorAction and -ErrorVariable are not supported. You have to check the $LASTEXITCODE variable for errors.

az aks get-credentials --resource-group $clusterrg --name $clustername
if( 0 -ne $LASTEXITCODE ) {
    Write-Error "Azure CLI failed with exit code $LASTEXITCODE"
    exit 1
}

You can find possible Azure CLI exit codes documented here.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.