Quantcast
Channel: The Official Scripting Guys Forum! forum
Viewing all articles
Browse latest Browse all 15028

Script to remove unlink GPOs

$
0
0

I'm trying to create a script that does the following: 1. List all unlink GPOs 2. Backup unlink GPOs 3. Delete unlink GPOs 4. Relist unlink GPOs. Can someone help me to clean the code up or improve it? Also, I keep getting this error: 

Get-GPOReport : Object reference not set to an instance of an object.
At C:\Users\452919\Downloads\Remove-UnlinkedGPO.ps1:15 char:82
+ Get-GPO -All | Sort-Object DisplayName | ForEach { $gpo = $_ ; $_ | Get-GPOReport <<<<  -ReportType xml | ForEach { I
f(IsNotLinked([xml]$_)){$unlinkedGPOs += $gpo} }}
    + CategoryInfo          : NotSpecified: (:) [Get-GPOReport], NullReferenceException
    + FullyQualifiedErrorId : System.NullReferenceException,Microsoft.GroupPolicy.Commands.GetGpoReportCommand

Here is my code:

import-module grouppolicy

function IsNotLinked($xmldata){
    If ($xmldata.GPO.LinksTo -eq $null) {
        Return $true
    }
    
    Return $false
}

$unlinkedGPOs = @()
$date = get-date -format M.d.yyyy 
New-Item -Path C:\Users\452919\Downloads\GPOBackups\$date -ItemType directory 

Get-GPO -All | Sort-Object DisplayName | ForEach { $gpo = $_ ; $_ | Get-GPOReport -ReportType xml | ForEach { If(IsNotLinked([xml]$_)){$unlinkedGPOs += $gpo} }}

If ($unlinkedGPOs.Count -eq 0) {
    "No Unlinked GPO's Found"
Backup-Gpo -All -Path C:\Users\452919\Downloads\GPOBackups\$date
}
Else{
    $unlinkedGPOs | Select DisplayName, ModificationTime, CreationTime| ft >> PreUnLinkedGPOs.txt
    Get-GPO -All | Sort-Object displayname | Where-Object { If ( $_ | Get-GPOReport -ReportType XML | Select-String -NotMatch “<LinksTo>” )
   {
     Backup-GPO -name $_.DisplayName -path C:\Users\452919\Downloads\GPOBackups\$date
     $_.Displayname | remove-gpo -Confirm
   }
  }
    $unlinkedGPOs | Select DisplayName, ModificationTime, CreationTime| ft >> UnLinkedGPOs.txt

}





Viewing all articles
Browse latest Browse all 15028

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>