gpt4 book ai didi

powershell - 继续执行异常

转载 作者:行者123 更新时间:2023-12-04 18:10:05 25 4
gpt4 key购买 nike

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

最佳答案

您使用 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)
}
}

关于powershell - 继续执行异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16229582/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com