0

I have the function get_user that searches for the username typed:

function get_user
{
    $url2 = "myurl/userName:" + $userName

    $contentType2 = "application/json"
    $basicAuth2 = post_token
    $headers2 = @{
              Authorization = $basicAuth2
             }
    $body2 = @{
              grant_type = 'client_credentials'
             }
    $getUser = Invoke-RestMethod -Method Get -Uri $url2 -ContentType $contentType2 -Headers $headers2 -Body $body2

    return $getUser.userName
}

And then I have my try/catch statement in the main method which is not working:

#MAIN

try {

$userName = Read-Host -Prompt "Input the user's username"
$getUser = get_user

    if ($userName -eq $getUser) 
        {
            $courseId = Read-Host -Prompt "Input the course's ID"
            $availability = Read-Host -Prompt "Available? (Yes/No)"
            $courseRoleId = Read-Host -Prompt "Course Role? (Student/Instructor)"

            $confirmationEnrollment = putStudentCourse
            " "
            "####################################################"
            "Success!"
            "####################################################"
        }       
    else
        {
            $firstName = Read-Host -Prompt "First Name"
            $lastName = Read-Host -Prompt "Last Name"
            $netId = $userName
            $email = $userName + "@school.edu"
            $password = Read-Host -Prompt "Password"
            $uin = Read-Host -Prompt "ID Number"
            $isAvailable = Read-Host -Prompt "Available? (Yes/No)"

            $confirmationUserCreate = user_create
            " "
            "####################################################"
            "User created!"
            "####################################################"
            " "
            $courseId = Read-Host -Prompt "Input the course's ID"

            $confirmEnroll = putStudentCourse
            " "
            "####################################################"
            "User enrolled!"
            "####################################################"
        }
    }
catch [System.Net.HttpWebRequest]
    {
        "####################################################"
        "User not found. We'll create it now!"
        "####################################################"
        " "
    }

Right now it is throwing error after you type a username that doesn't exist:

Invoke-RestMethod : The remote server returned an error: (404) Not Found.
At E:\Blackboard_REST_API_Project\PowerShell\Post_Student_Course.ps1:42 char:13
+     $getUser = Invoke-RestMethod -Method Get -Uri $url2 -ContentType $contentType2  ...
+    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

I am trying to hide the red error and output what I have in the catch statement but it is skipping the catch and jumping straight to the else when it can't find a username. Any ideas?

3
  • Hi emanresu. That catches the error and outputs what's inside the catch statement, awesome! The only issue is that it terminates the program and it doesn't go to the else statement Commented Apr 6, 2017 at 16:25
  • You are probably catching the wrong exception type. In addition to that I don't think this code will do what you want. If get_user throws an error then you are skipping the section of code that contains the "user created" text. Do you mean to create the user when an error occurs? Commented Apr 6, 2017 at 16:26
  • Correct. If the user is found, go ahead with the if statement (ask for a course ID and it will enroll the user, I have another function for that). If it doesn't, jump to the else statement and create the user. Commented Apr 6, 2017 at 16:27

2 Answers 2

2

You're checking for the wrong exception-type in your catch-statement. A 404 error is thrown as a WebException:

$Error[0]
Invoke-RestMethod : The remote server returned an error: (404) Not Found.
At line:2 char:5
+     Invoke-RestMethod -Uri "http://www.vg.no/nonexistingpage"
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

$Error[0].Exception

The remote server returned an error: (404) Not Found.

$Error[0].Exception.GetType().FullName

System.Net.WebException

Try:

try {
    Invoke-RestMethod -Uri "http://www.vg.no/nonexistingpage"
}
catch [System.Net.WebException]
{
    "Exception caught!"
}

As for the script, I would probably do something like this to make create the user if it doesn't (404-error):

#MAIN

$userName = Read-Host -Prompt "Input the user's username"

try {
    $getUser = get_user
} catch [System.Net.WebException] {
    #User doesn't exist, create new
    $firstName = Read-Host -Prompt "First Name"
    $lastName = Read-Host -Prompt "Last Name"
    $netId = $userName
    $email = $userName + "@school.edu"
    $password = Read-Host -Prompt "Password"
    $uin = Read-Host -Prompt "ID Number"
    #Is it required to create user? If not, remove as it's specified later
    $isAvailable = Read-Host -Prompt "Available? (Yes/No)"

    $confirmationUserCreate = user_create
    " "
    "####################################################"
    "User created!"
    "####################################################"

    #Verify user was created
    $getUser = get_user
}

#Not sure if test is still needed..
if($userName -eq $getUser) {
    $courseId = Read-Host -Prompt "Input the course's ID"
    $availability = Read-Host -Prompt "Available? (Yes/No)"
    $courseRoleId = Read-Host -Prompt "Course Role? (Student/Instructor)"

    $confirmationEnrollment = putStudentCourse
    " "
    "####################################################"
    "Success!"
    "####################################################"
}

Tip: You should use parameters in your functions and not rely on variables that might exist.

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

1 Comment

Good idea including a snippet showing how to get the name of the exception type.
0

Regarding the Try Catch the most likely cause is that an error other than the one listed explicitly after the Catch is occurring. The way to test this is to remove the named exception type and just catch all errors. I am not recommending doing this in production code, but for testing it will at least reveal if your general idea is correct. Then you can clarify what specific errors to catch.

There seems to be some confusion about the desired actions. Based on comments below the question and based on your code comments you seem to be saying that if the request throws an error then the user must not exist and should be created. If this is correct be careful as that assumption won't always be true.

Once the error is thrown you will in fact skip all of the code in your If Else structure. Essentially I think you want to take the logic in your ELSE statement and move this into the Catch block. If it is the case that you want to try to create the user either if get_user throws an error or if it doesn't throw an error but the If condition fails then you will want the same logic in the else AND in the catch. Of course it would be better to create a function to call from either rather than duplicating code.

Essentially:

Try{
    #try to invoke the request

    #if the request did not fail then compare the user entered text to the text returned from the request
    #if these match then user already exists
    #else the user does not exist so create it here
}
catch{
  #if the request failed assume that the user does not exist and create it here

}

1 Comment

Thank you emanresu. It was a syntax issue. I deleted the error type from the catch statement and moved the else to the catch statement and it works great!

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.