继续执行Exception

Ish*_*han 5 error-handling powershell continue

下面是我想要执行的脚本.这里的问题是一旦发生异常就会停止执行,我continue在catch块中使用但是没有用.即使在发生异常后它如何循环,我如何使它工作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)
} 
Run Code Online (Sandbox Code Playgroud)

请帮助.

Ans*_*ers 7

try {...} catch {...}希望处理错误时使用.如果要忽略它们,则应将$ErrorActionPreference = "Continue"(或"SilentlyContinue")设置为@CB建议,或者-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)
  }
} 
Run Code Online (Sandbox Code Playgroud)

  • 由于我想记录非终止错误,设置'$ ErrorActionPreference'对我没什么帮助.只有它工作的时间是'$ ErrorActionPreference ="Stop"',但是执行停止了.我想在错误时继续执行.请看我的回答,这解决了我的问题.感谢您的回答.:) (2认同)