继续执行Exception

时间:2013-04-26 05:51:22

标签: powershell error-handling continue

以下是我想要执行的脚本。这里的问题是一旦发生异常就会停止执行,我在catch块中使用了continue但是没有用。即使发生异常,我如何才能使它工作,它应该在foreach循环。

我还使用了while($true)循环但是进入了无限循环。怎么去呢?

$ErrorActionPreference = "Stop";
try 
{
# Loop through each of the users in the site
foreach($user in $users)
{
    # Create an array that will be used to split the user name from the domain/membership provider
    $a=@()


    $displayname = $user.DisplayName
    $userlogin = $user.UserLogin


    # Separate the user name from the domain/membership provider
    if($userlogin.Contains('\'))
    {
        $a = $userlogin.split("\")
        $username = $a[1]
    }
    elseif($userlogin.Contains(':'))
    {
        $a = $userlogin.split(":")
        $username = $a[1]
    }

    # Create the new username based on the given input
    $newalias = $newprovider + "\" + $username

    if (-not $convert)
    {
        $answer = Read-Host "Your first user will be changed from $userlogin to $newalias. Would you like to continue processing all users? [Y]es, [N]o"

        switch ($answer)
        {
            "Y" {$convert = $true}
            "y" {$convert = $true}
            default {exit}
        }
    }   

    if(($userlogin -like "$oldprovider*") -and $convert)
    {  

        LogWrite ("Migrating User old : " + $user + " New user : " + $newalias + "    ")
        move-spuser -identity $user -newalias $newalias -ignoresid -Confirm:$false
        LogWrite ("Done")
    }   
} 
}
catch  {
    LogWrite ("Caught the exception")
    LogWrite ($Error[0].Exception)
} 

请帮助。

4 个答案:

答案 0 :(得分:7)

如果要处理错误,请使用try {...} catch {...}。如果您想忽略它们,则应将$ErrorActionPreference = "Continue"(或"SilentlyContinue")设置为@ C.B.建议,或使用-ErrorAction "SilentlyContinue"进行引发错误的特定操作。如果你想处理某条指令的错误,你可以将该指令放在try {...} catch {...}块中,而不是整个循环中,例如:

foreach($user in $users) {
  ...
  try {
    if(($userlogin -like "$oldprovider*") -and $convert) {  
      LogWrite ("Migrating User old : " + $user + " New user : " + $newalias + "    ")
      move-spuser -identity $user -newalias $newalias -ignoresid -Confirm:$false
      LogWrite ("Done")
    }   
  } catch {
    LogWrite ("Caught the exception")
    LogWrite ($Error[0].Exception)
  }
} 

答案 1 :(得分:0)

修改代码如下。在move-spuser -identity $user -newalias $newalias -ignoresid -Confirm:$false

之后使用以下代码
if($?)
{
  LogWrite ("Done!")
  LogWrite ("  ")
}
else
{
  LogWrite ($Error[0].ToString())
  LogWrite ("  ")
}

答案 2 :(得分:0)

对我有用的是将$ErrorActionPreference变量设置为停止,然后将其重置为在catch块中继续:

$e = $ErrorActionPreference
$ErrorActionPreference="stop"

try
{
     #Do Something that throws the exception
}
catch
{
    $ErrorActionPreference=$e

}

$ErrorActionPreference=$e;

答案 3 :(得分:0)

您似乎已将“捕获”放置在循环主体之外,因此中止了循环。将渔获物放入循环中