PowerShell: Retrieve Group Policy details for Remote Computer

 

There are multiple scenarios as a part of AD management where we need to retrieve Group Policy information for managed computers. There are generally two methods to get the information.

Method 1:

Most common method is to use gpresult.exe command which is detailed in this technet article. This works well only if that User executing the command has logged-in once at-least in the target computer. Else it throws below error.

The user does not have RSOP Data

Method 2:

Method 2 is to use Get-GPResultantSetOfPolicy PowerShell command-let which is detailed here. This command also works similar to Method 1 and requires User to login at-least once.

Using Method 1 and Method 2, even if we want the group policy information only for the computer irrespective of user, it is not possible without the user logged in at-least once as the command retrieves resulting set of policies that are enforced for specified user on the target computer.

 

Solution:

To overcome these issues, using Group Policy Management COM Object which is the base for gpresult.exe and Get-ResultantSetOfPolicy PS command-let serves better. We can use the COM object in VB or PS scripting. Here we will discuss about using it in PS Scripting.

#Initialize Variables

$OutputFile = “C:\Temp\GPOExport.html”

$ComputerName = “test.contoso.com”

$UserName = “john”

The first thing we do is create an instance of the GPMgmt.GPM object. We can use this object if the Group Policy Management Console is installed in the computer.

$gpm = New-Object -ComObject GPMgmt.GPM

Next step is to obtain all constants and save it in a variable.

$constants = $gpm.GetConstants()

Now create reference RSOP object using required constants.

$gpmRSOP = $GPM.GetRSOP($Constants.RSOPModeLogging,$null,0)

Next step is to specify Target Computer and User.

$gpmRSOP.LoggingComputer = $ComputerName

$gpmRSOP.LoggingUser = $UserName

Note: If we need the RSOP data for only Computer without considering User imposed Group Policy data, we need to use “RsopLoggingNoUser” constant value instead of $gpmRSOP.LoggingUser.

$gpmRSOP.LoggingFlags = $Constants.RsopLoggingNoUser

Next step is to query the target computer for RSOP GPO data.

$gpmRSOP.CreateQueryResults()

To export data to a output file below command is used.

HTML:

$gpmRSOP.GenerateReportToFile($constants.ReportHTML,$outputfile)

XML:

$gpmRSOP.GenerateReportToFile($constants.ReportXML,$outputfile)

Thus using GPMgmt.GPM COM object, we can obtain Resulting Set of Group Policies for Target Computer with or without considering the User and also without requirement of user logging at-least once.

 

Happy Scripting :-)