+49 8033 303222

Powershell – replace linked GPOs by name

Beschreibung:

das Script sucht in der Domain ( Variable $domain) nach allen OUs auf die eine GPO ( Variable $GpoName ) verlinkt ist und ersetzt diese durch eine neue GPO ($NewGpoName) an der gleichen Position (Link Order) der jeweiligen OU

 

function ConvertFrom-DN
{
param([string]$DN=(Throw '$DN is required!'))
    foreach ( $item in ($DN.replace('\,','~').split(",")))
    {
        switch -regex ($item.TrimStart().Substring(0,3))
        {
            "CN=" {$CN = '/' + $item.replace("CN=","");continue}
            "OU=" {$ou += ,$item.replace("OU=","");$ou += '/';continue}
            "DC=" {$DC += $item.replace("DC=","");$DC += '.';continue}
        }
    }
    $canoincal = $dc.Substring(0,$dc.length - 1)
    for ($i = $ou.count;$i -ge 0;$i -- ){$canoincal += $ou[$i]}
    $canoincal += $cn.ToString().replace('~',',')
    return $canoincal
}
 
function ConvertFrom-Canonical
{
param([string]$canoincal=(trow '$Canonical is required!'))
    $obj = $canoincal.Replace(',','\,').Split('/')
    [string]$DN = "OU=" + $obj[$obj.count - 1]
    for ($i = $obj.count - 2;$i -ge 1;$i--){$DN += ",OU=" + $obj[$i]}
    $obj[0].split(".") | ForEach-Object { $DN += ",DC=" + $_}
    return $dn
}
 
$GUIDRegex = "{[a-zA-Z0-9]{8}[-][a-zA-Z0-9]{4}[-][a-zA-Z0-9]{4}[-][a-zA-Z0-9]{4}[-][a-zA-Z0-9]{12}}"           
$GpoName = "Old_GPO_Name"
$NewGpoName = "New_GPO_Name"
$domain = "nwtraders.com"
 
[xml]$gpocontent  = get-gporeport -name $GpoName  -domain $domain -ReportType xml
$LinksPaths = $gpocontent.GPO.LinksTo #| %{$_.SOMPath}
 
foreach ( $link in $linkspaths )
{
    $ou = ConvertFrom-Canonical $link.SOMPath
    $linkedGPOs = (Get-GPInheritance -Target $ou).gpolinks
    foreach ($link in $LinkedGPOs ) {
       if ( $link.DisplayName -eq $GpoName ) {
          write-host $link.DisplayName $link.Order
          $linkOrder = $link.Order
          New-GPLink -Name $NewGpoName -Target $ou -LinkEnabled Yes -Order $linkOrder -Domain $domain
          Remove-GPLink -Name $GpoName -Target $ou -Domain $Domain
       }
    }
}