7

下面是我要执行的脚本。这里的问题是一旦发生异常就会停止执行,我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)
} 
4

4 回答 4

10

try {...} catch {...}当你想处理错误时使用。如果您想忽略它们,您应该按照@CB 的建议设置$ErrorActionPreference = "Continue"(或),或用于引发错误的特定操作。如果您想处理来自某个指令的错误,您应该将该指令放在块中,而不是整个循环中,例如:"SilentlyContinue"-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)
  }
} 
于 2013-04-26T07:51:07.763 回答
1

您似乎已将“catch”放在循环体之外,从而中止循环。将 catch 放入循环中

于 2019-08-16T20:37:18.530 回答
0

修改代码如下。之后使用了以下代码move-spuser -identity $user -newalias $newalias -ignoresid -Confirm:$false

if($?)
{
  LogWrite ("Done!")
  LogWrite ("  ")
}
else
{
  LogWrite ($Error[0].ToString())
  LogWrite ("  ")
}
于 2013-04-26T07:55:30.600 回答
0

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

$e = $ErrorActionPreference
$ErrorActionPreference="stop"

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

}

$ErrorActionPreference=$e;
于 2014-11-24T20:10:41.193 回答