We had a need to enable and disable groups of GPOs on a recurring basis and wanted to automate the process.
This script relies on the BSonPosh module. It also relies on the Windows PowerShell Group Policy cmdlets. The Group Policy cmdlets are on Windows 2008 R2 DCs, a server with the GPMC installed, or Windows 7 with the RSAT installed.
To use the script, create a text file with the name of each GPO that you want to control via the script. The script takes 2 parameters, whether to enable or disable the GPOs, and the name of the textfile with the list of GPOs.
Param( #Enabled or Disabled, whether you want the GPOs enabled or disabled [string]$GPOStatus = $(Throw '$GPOStatus is required'), #List of GPOs to enable/disable [string]$GPOList = $(Throw '$GPOList is required') ) Process { $GPO_DISABLED = "AllSettingsDisabled" $GPO_ENABLED = "AllSettingsEnabled" #Change the specified GPO's GpoStatus property function SetGPOStatus( [string]$GPOName, [string]$Status ) { $gpo=Get-GPO $GPOName -server $PDC.ServerName -errorAction SilentlyContinue if ( $gpo -eq $null ) { write-host "Could not locate" $GPOName } else { $gpo.GpoStatus = $Status Write-Host "Set"$gpo.DisplayName"to"$gpo.GpoStatus } } #Attempt to load a module with Import-Module function TryImportModule( [string]$ModuleName ) { if ( (Get-Module $ModuleName ) -eq $null ) { Import-Module $ModuleName if ( (Get-Module $ModuleName ) -eq $null ) { Write-Host "Unable to load module" $ModuleName return $false } } return $true } # Microsoft module to manage Group Policy $retval = TryImportModule "grouppolicy" if ( $retval -eq $false ) { return } # Community module that will help retrieve FSMO roles $retval = TryImportModule "bsonposh" if ( $retval -eq $false ) { return } # Modify the GPOs on the server with the PDC Master FSMO role $PDC = Get-Fsmo -role "PDCMaster" -errorAction SilentlyContinue if ( $PDC -eq $null ) { write-host "Could not locate PDC Master" return } # Validate Status flag input if ( $GPOStatus.ToLower() -eq "disabled" ) { $SetFlag = $GPO_DISABLED } elseif ( $GPOStatus.ToLower() -eq "enabled" ) { $SetFlag = $GPO_ENABLED } else { Write-Host "Invalid value '$GPOStatus' for paramGPOStatus. Allowed values: [Disabled|Enabled]". return } # Ensure we actually have a list of GPOs in our text file if ( (Test-Path $GPOList) -eq $false ) { write-host "Could not locate"$GPOList return } else { $AllGPOs = Get-Content $GPOList if ( $AllGPOs -eq $null ) { write-Host $GPOList" is empty." return } foreach ( $myGPO in $AllGPOs ) { if ( $myGPO.SubString(0,1) -ne "#" ) #Allows comments in the text file { SetGPOStatus $myGPO $SetFlag } } } } |
Example usage: .\SetGPOStatus.ps1 -GPOStatus “Disabled” -GPOList “gpolist.txt”