Try / Catch无法在PowerShell中运行

时间:2017-04-06 16:07:41

标签: powershell try-catch

我有get_user函数,用于搜索输入的用户名:

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
}

然后我在main方法中使用了try / catch语句:

#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!"
        "####################################################"
        " "
    }

现在,在您输入不存在的用户名后,它会抛出错误:

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

我正在尝试隐藏红色错误并输出我在catch语句中的内容,但是当它无法找到用户名时,它会跳过捕获并直接跳到其他地方。有什么想法吗?

2 个答案:

答案 0 :(得分: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.

答案 1 :(得分:0)

关于Try Catch,最可能的原因是在Catch发生后明确列出的错误之外的错误。测试它的方法是删除命名的异常类型并捕获所有错误。我不建议在生产代码中执行此操作,但对于测试,它至少会揭示您的一般想法是否正确。然后,您可以澄清要捕获的具体错误。

对于所期望的行动似乎存在一些混淆。根据问题下方的注释并根据您的代码注释,您似乎在说如果请求引发错误,则用户必须不存在并且应该创建。如果这是正确的,要小心,因为这个假设永远不会成真。

一旦抛出错误,您实际上会跳过If Else结构中的所有代码。基本上我认为你想要在ELSE语句中采用逻辑并将其移动到Catch块中。如果你想尝试创建用户,如果get_user抛出一个错误,或者它没有抛出错误,但If条件失败,那么你将需要在catch中的else AND中使用相同的逻辑。当然,最好是创建一个函数来调用而不是复制代码。

本质:

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

}