vendredi 31 mars 2017

Try/Catch Nested If/Else Statement in PowerShell

I am trying to write a try/catch statement for my PowerShell script nested in an if/else statement. I am not getting any errors however, I think there's something wrong with my syntax. Right now, my main function of the script looks like this:

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

$getUser = get_user

if ($userName -eq $getUser) 
    {
        try
        {
        $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!"
        "####################################################"
        }
        catch
        {
            [WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand]
            "####################################################"
            "User not found. We'll create it now!"
            "####################################################"
            " "
        }
    }
    else
    {
        $firstName = Read-Host -Prompt "First Name"
        $lastName = Read-Host -Prompt "Last Name"
        $netId = $userName
        $email = $userName + "@school.edu"
        $password = Read-Host -Prompt "Password"
        $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!"
        "####################################################"
    }

If the user isn't found it throws this error:

Invoke-RestMethod : The remote server returned an error: (404) Not Found.
At E:\PowerShell\Post_Student_Course.ps1:37 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

What I am trying to do is output this:

"####################################################"
"User not found. We'll create it now!"
"####################################################"
" "

Instead of the red error. Any ideas how can I fix this?

Best regards,

Aucun commentaire:

Enregistrer un commentaire