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 grouppolicyfunction 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
}