0

我想组合下面的脚本,以便它可以自动复制 AD 数据库内容,而无需等待 15 分钟,仅适用于所有在线域控制器。

function Replicate-AllDomainController
{
    (Get-ADDomainController -Filter *).Name | Foreach-Object { repadmin /syncall $_ (Get-ADDomain).DistinguishedName /e /A | Out-Null }; Start-Sleep 10; Get-ADReplicationPartnerMetadata -Target "$env:userdnsdomain" -Scope Domain | Select-Object Server, LastReplicationSuccess
}

function Test-AllDomainController
{
    $dcs = (Get-ADDomainController -Filter *).Name
    foreach ($items in $dcs)
    {
        Test-Connection $items -Count 1
    }
}

Try
{
    Where-Object (Test-AllDomainController)
    {
        Replicate-AllDomainController
    }
}
Catch
{
    Write-Output "Exception Type: $($_.Exception.GetType().FullName)"
    Write-Output "Exception Message: $($_.Exception.Message)"
}

如何正确执行,以便在成功复制最后一个 AD DC 后停止,没有问题?如果有问题,请在单独的 Out-GridView 中显示有问题的 AD 域控制器。

4

1 回答 1

1

我自己无法对此进行测试,但我认为最好在try{}..catch{}调用 repadmin.exe 的函数内部进行。

此外,在同一个函数中,测试是否可以使用 访问服务器会更简单Test-Connection,因此您可以使用一个函数来做这两件事:

# create a list to collect errors
$errorList = [System.Collections.Generic.List[object]]::new()

function Replicate-AllDomainController {
    (Get-ADDomainController -Filter *).Name | Foreach-Object { 
        # put the servername from the $_ automatic variable in a variable of your own, because when you
        # hit the catch block, inside there the $_ is the Exception object and no longer the server name.
        $dc = $_
        if (Test-Connection $dc -Count 1 -Quiet) {
            try {
                repadmin /syncall $dc (Get-ADDomain).DistinguishedName /e /A | Out-Null
            }
            catch {
                # the $errorList is available here using the script scope
                $script:errorList.Add(
                    [PsCustomObject]@{
                        'Server'            = $dc
                        'Exception Type'    = $_.Exception.GetType().FullName
                        'Exception Message' = $_.Exception.Message
                    }
                )
            }
        }
        else {
            Write-Warning "Server '$dc' cannot be reached"
        }
    }
    Start-Sleep -Seconds 10
    Get-ADReplicationPartnerMetadata -Target "$env:userdnsdomain" -Scope Domain | Select-Object Server, LastReplicationSuccess
}

# call the function
Replicate-AllDomainController

# check if there were replication errors
if ($errorList.Count) {
    # if there were errors, show them in a separate GridView
    $errorlist | Out-GridView -Title "Replication errors"
}
else {
    Write-Host "All done; no errors reported" -ForegroundColor Green
}
于 2020-07-16T10:51:48.090 回答