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?