Quantcast
Channel: Group Policy Team Blog
Viewing all 56 articles
Browse latest View live

How to add comment for a GPO with PowerShell

$
0
0

You might have seen GP MVP Jeremy Moskowitz’s post on how to recycle GPO comments. While Jeremy points out you can do this without a script…. You can also do it with a script! Our tech writer, Judith, walks us through the process:

 

After I import the Group Policy module in PowerShell, I have access to the Get-GPO cmdlet. If I run that to create an object representing my test GPO:

PS C:\ >$testGPO= Get-GPO testGPO PS C:\ >$testGPO DisplayName : testGPO DomainName : corp.contoso.com Owner : CORP3\Domain Admins Id : 4364e8c5-23a0-4020-9624-4dbcaac9c8c2 GpoStatus : AllSettingsEnabled Description : CreationTime : 5/9/201110:07:09 AM ModificationTime : 6/27/20113:51:20 PM UserVersion : AD Version: 1, SysVol Version: 1 ComputerVersion : AD Version: 1, SysVol Version: 1 WmiFilter :

 

 

I was pretty sure that Description would show the comment for the GPO. And I ran the Get-Member cmdlet against the $testGPO object just to verify that I can use the Description property to set the comment using PowerShell.

 

PS C:\ >$testGPO| gm -Membertype property TypeName: Microsoft.GroupPolicy.Gpo Name MemberType Definition ------------------------ Computer Property Microsoft.GroupPolicy.ComputerConfiguration Computer {get;} CreationTime Property System.DateTime CreationTime {get;} Description Property System.String Description {get;set;} DisplayName Property System.String DisplayName {get;set;} DomainName Property System.String DomainName {get;} GpoStatus Property Microsoft.GroupPolicy.GpoStatus GpoStatus {get;set;} Id Property System.Guid Id {get;} ModificationTime Property System.DateTime ModificationTime {get;} Owner Property System.String Owner {get;} Path Property System.String Path {get;} User Property Microsoft.GroupPolicy.UserConfiguration User {get;} WmiFilter Property Microsoft.GroupPolicy.WmiFilter WmiFilter {get;set;}

Then I changed the comment by setting $testGPO.Description to a string value, which just looks like a simple assignment:

PS C:\ >$testGPO.description="This is my test GPO. I'm using this to try out GP and PowerShell." PS C:\ >$testGPO DisplayName : testGPO DomainName : corp.contoso.com Owner : CORP3\Domain Admins Id : 4364e8c5-23a0-4020-9624-4dbcaac9c8c2 GpoStatus : AllSettingsEnabled Description : This is my test GPO. I'm using this to try out GP and PowerShell. CreationTime : 5/9/201110:07:09 AM ModificationTime : 6/27/20113:51:20 PM UserVersion : AD Version: 1, SysVol Version: 1 ComputerVersion : AD Version: 1, SysVol Version: 1 WmiFilter :

Here’s the GPMC snapshot before changing the comment:

clip_image002

And here’s the GPMC snapshot after I changed the comment:

clip_image004


New! Windows PowerShell Help on TechNet

$
0
0

I know there's a lot of interest around Windows PowerShell. Here's some information you might be interested in as a Group Policy Administrator:

If you are now looking for information to help you understand and learn Windows PowerShell, then you can find new help on TechNet at: http://technet.microsoft.com/en-us/library/bb978526.aspx

And you can find the Windows PowerShell Programmer's Guide that provides tutorials for creating cmdlets, providers, and hosting applications at: http://go.microsoft.com/fwlink/?LinkID=89596

The Windows PowerShell User Assistance team is looking for feedback on the documentation. Please send your feedback to tellPSUA@microsoft.com

Also, if you've found other good references for Group Policy and Windows PowerShell please add the information using the comments link below.

Group Policy in Windows 7

$
0
0

PowerShell! The name alone should get you excited. Wait until you see all the cool stuff you can do with PowerShell in the Windows Server 2008 R2 and Windows 7 release of the Group Policy management tools. For those of you who have yet to learn PowerShell, hopefully this will help motivate you. You will be able to…

 

a)      Add PowerShell scripts to logon/logoff and startup/shutdown

b)      Use cmdlets to do a lot of what you’ve been using the GPMC UI or GPMC Sample Scripts for (creating new GPO’s, linking, making backups…)

 

<drumroll please…>

 

c)       Configure GPO registry settings from the PowerShell commandline

 

Holy cow! If you aren’t excited, it’s only because you don’t know what the word cmdlet is yet, but you can find out!

 

Here’s how:

 

Don Jones is a great writer for people of every level:

               

Here are some of his great reasons to use PowerShell with some cool tricks you can use right away for troubleshooting and management:

http://technet.microsoft.com/en-us/magazine/cc160873.aspx

Check this out from the article:

 

Top 10 Cmdlets to Start Using Immediately
  • Get-Command retrieves a list of all available cmdlets.
  • Get-Help displays help information about cmdlets and concepts.
  • Get-WMIObject retrieves management information by using WMI.
  • Get-EventLog retrieves Windows event logs.
  • Get-Process retrieves a single or list of active processes.
  • Get-Service retrieves a Windows service.
  • Get-Content reads in text files, treating each line as a child object.
  • Add-Content appends content to a text file.
  • Copy-Item copies files, folders, and other objects.
  • Get-Acl retrieves access control lists (ACLs).

For a complete list of cmdlets that ship with Windows PowerShell, go to windowssdk.msdn.microsoft.com/en-us/library/ms714408.aspx

 

 

 

Here, he’s showing you how to build a software inventory tool using WMI cmdlets in a 6 minute video with accompanying article:

http://blogs.technet.com/tnmag/archive/2008/10/21/windows-powershell-building-your-own-software-inventory-tool.aspx

 

 

The Scripting Guys are hilarious and helpful.  This is some of the stuff I liked that they wrote:

 

Get-Service; a quick way to get your hands dirty with something you can use right away

http://www.microsoft.com/technet/scriptcenter/topics/msh/cmdlets/get-service.mspx

 

Format-List; how to make your results useful to you

http://www.microsoft.com/technet/scriptcenter/topics/msh/cmdlets/format-list.mspx

 

This is their archive of Windows PowerShell Tips:

http://www.microsoft.com/technet/scriptcenter/resources/pstips/archive.mspx

 

Let me know what resources you like in the comments, I can always learn more.  Keep looking to this blog for more details on GP’s new cmdlets…

 

Hope this helps,

 

Lilia Gutnik

Group Policy, PM

Introduction to Windows PowerShell Cmdlets in Windows 7

$
0
0

New Year, New…console session? Here’s a quick look at creating a new GPO using the Group Policy cmdlets in Windows 7.

 

To create a new GPO from scratch using PowerShell cmdlets:

 

1.       Open an elevated PowerShell console session  (1-2 clicks)

2.       Command: Import-Module grouppolicy (typing)

3.       Command: New-GPO “Sales GPO” (typing)

 (optional: add parameter –starter “Security Starter”)

       Total: 1-2 clicks, 2 lines of typing

 

To create a new GPO from scratch using the UI:

 

1.       Open the GPMC (1-2 clicks)

2.       Navigate to the domain of your target domain (1-2 clicks)

3.       Open the Group Policy Objects Folder (1 click)

b.      Right click, and select “New”  (2 clicks)

or

c.       Alternatively, go to Action-> New from the title bar (2 clicks)

4.       Enter a name “Sales GPO” (typing)

(Optional: Select a Starter GPO from the Drop Down)

5.       Select OK (1 click)

Total: 6-8 clicks, one line of typing

 

The PowerShell cmdlet example assumes several things:

·         The domain that you are logged onto is where you would like to create your new GPO. Otherwise, you can specify the domain you’d like to create the GPO in with the optional –domain parameter (FQDN) and target the DC of your choice with the server parameter.

·         GPMC is installed on the machine (Win7 server or Win7 client with RSAT) you are working from

In general, the cmdlet method requires more typing, but far fewer steps and clicks. The additional benefit is the accuracy and ease of repetition: after the initial start up, creating a second GPO is even faster from the PowerShell console. The click-through UI method requires most of the same steps. However, if you capture the cmdlet commands in a script, re-running that script is one command; running that script 100 times is only marginally more effort and assured to produce the same results.

If you don’t have the beta to play around with the Group Policy cmdlets yet, you should check out Darren Mar-Elia’s cmdlets that his company SDMSoftware released.  His site, www.gpoguy.com, has helpful videos, articles, and tools to help you work with Group Policy.  Check that site out regardless, beta or not. It’s got a lot of good information for every level of GP knowledge.

Group Policy Cmdlets, Replication & the '-Server' Parameter

$
0
0

Hello GP Junkies! My name is Bryan Garretson, and I want to let you know about an interesting way we were able to leverage the new PowerShell cmdlets available in Windows Server 2008 R2 / Windows 7: to anticipate and test around replication delays in certain configurations.

 

When we were testing RODC read ops, we needed to create our data (GPOs/settings/permissions... GP cmdlets do it all) on a DC (ServerA); it's a PDC for the domain. Then, we tried to read that data from the test target (ServerB): an RODC member server in the same domain. You may know where this is going... we got cascading test failures because the data we created on the PDC hadn't yet replicated. The solution? We had to create a mechanism to effectively 'WaitOnReplication' in our scripts/automation, before proceeding with validation.

 

Consider the following script: 

 

##############WaitOnReplication.ps1##############

$ErrorActionPreference = "SilentlyContinue"

 

###Create the source GPO on the PDC

New-GPO -Name "TestingIsFun" -Domain myTestDomain.com -Server ServerA.myTestDomain.com

 

###Quick check to verify it exists before trying to do the RODC read

$srcGPO = (Get-GPO -Name "TestingIsFun" -Domain myTestDomain.com -Server ServerA.myTestDomain.com)

 

if($srcGPO)

{

       ###Write success to console

       $srcGPOExists

       

       $iCtr=0

       $myGPO;

 

       ###While RODC-based GPO is null, retry

       while(!$myGPO)

       {

           $iCtr++       

            

           $myGPO = (Get-GPO -Name "TestingIsFun" -Domain myTestDomain.com -Server ServerB.myTestDomain.com)

 

           ###Adjust the interval to reduce console noise, or use a timer

           if(($iCtr%50) -eq (0)){ $iCtr }

 

           ###Print out RODC-read GPO details after populated (meaning, replication took place)            

           if($myGPO)

           {

              ""

              $myGPO

           }

 

       }

      

       ###Once out of the loop we are successful!

       $targetReadSuccess = "Target read Successfully! Replication has taken place"

       $targetReadSuccess

 

}

#################################################

 

[Output]

PS D:\test> D:\test\WaitOnReplication.ps1

 

DisplayName      : TestingIsFun

DomainName       : myTestDomain.com

Owner            : myTestDomain\Domain Admins

Id               : fea7672e-ba81-4588-82c6-dcb30c7eb81e

GpoStatus        : AllSettingsEnabled

Description      :

CreationTime     : 2/19/2009 10:14:38 AM

ModificationTime : 2/19/2009 10:14:38 AM

UserVersion      : AD Version: 0, SysVol Version: 0

ComputerVersion  : AD Version: 0, SysVol Version: 0

WmiFilter        :

 

50

... ...

950

 

DisplayName      : TestingIsFun

DomainName       : myTestDomain.com

Owner            : myTestDomain\Domain Admins

Id               : fea7672e-ba81-4588-82c6-dcb30c7eb81e

GpoStatus        : AllSettingsEnabled

Description      :

CreationTime     : 2/19/2009 10:14:38 AM

ModificationTime : 2/19/2009 10:14:52 AM

UserVersion      : AD Version: 0, SysVol Version: 0

ComputerVersion  : AD Version: 0, SysVol Version: 0

WmiFilter        :

 

Target read successfully! Replication has taken place

 

... now, at this point we know for certain that replication has taken place (at least, for the specified -Server) before proceeding with any other operation. What I'm trying to say is, there is a PowerShell-based method for determining whether or not replication has taken place, and the API granularity that is needed to accomplish that is provided for by the -Server parameter (also known by its alias '-DC').

Cheers,
Bryan

Software Design Engineer in Test, Group Policy

PowerShell Script: Backup all GPOs that have been modified this month

$
0
0

The scene: Backups take up space, but they’re a crucial part of GPO management. Ideally, one would do regular backups (monthly? weekly? your call) but only of the GPOs that have changed. This script will do that for you and print out a nice settings report of each GPO as it’s being backed up.

The following PowerShell script uses the Group Policy PowerShell cmdlets in Windows Server 2008 R2 (Windows 7 Client) to back up GPOs in the domain of the local computer that have been modified within the last month. After each GPO has been backed up, a settings report is generated for each GPO (much easier to read than the backup report).

Copy the following text and save it as a .ps1 file. The # symbols denote comments, so they won’t be run.

# The following script finds all GPOs in the domain that have been modified this month. It then takes these GPOs backs them up and generates a settings report  for each. Finally it lists out all of the GPOs that were backed up.
## it depends on being opened from the Active Directory provider shortcut to the PowerShell console, or navigating to that AD provider first

# necessary for any work with group policy cmdlets if ‘import-module’ fails, use ‘add-module’
import-module grouppolicy

#get all GPO's linked in the local computer’s domain
#first step is to get the domain object
# enter "get-ADDomain -?" for help

$mydomain = get-ADDomain -current LocalComputer

# the next step gets all the GPO's currently in the domain that have been modified this month

$currentDate = get-Date

$ModGPOs = get-gpo -domain $mydomain.DNSRoot -all | where {$_.ModificationTime.Year.equals($currentDate.Year) -And $_.ModificationTime.Month.equals($CurrentDate.Month)}

# loop through GPOs

$RootPath = "C:\GPOBackup\Reports\"

Foreach ($GPO in $ModGPOs) {
    # Backup the GPO to the specified path
    $GPOBackup = backup-GPO $GPO.DisplayName -path "C:\GPOBackup"

    # First build the Report path, then generate a report of the backed up settings.
    $ReportPath = $RootPath + $GPO.ModificationTime.Month + "-"+ $GPO.ModificationTime.Day + "-" + $GPO.ModificationTime.Year + "_" +  $GPO.Displayname + "_" + $GPOBackup.Id + ".html"
    get-GPOReport -Name $GPO.DisplayName -path $ReportPath -ReportType HTML
}

# Output which GPOs that have been successfully backed up.

"The following " + $ModGPOs.count + " GPOs were successfully backed up:" | out-host

Foreach ($GPO in $ModGPOs) {
    "          " + $GPO.DisplayName | out-host
}

"Go to " + $RootPath + " to view the settings reports for the backed up GPOs." | out-host

Some of you may have seen this at TEC 2009, hope you find this helpful. 

Mark Gray (Group Policy PM)

Set a registry key value from the command line using Group Policy PowerShell cmdlets

$
0
0

The scene: You want to set a registry key of a 3rd party application but you don’t want to write a custom ADMX file just to be able to configure it. Or you have some registry keys you set in logon scripts and you want to use the update interval of Group Policy to make sure that value sticks. Or you want to set 50 registry keys and you don’t want to do it all manually. Any of these scenarios lead to using the set-GPRegistryValue PowerShell cmdlet that ships as part of the Windows Server 2008 R2 GPMC. Here’s the step by step:

How To: Configure a registry key value in a GPO from the PowerShell commandline

1. Open the PowerShell prompt

There are 2 options for this. The standard PowerShell prompt and the shortcut to the Active Directory Provider.

The PowerShell prompt needs to opened with elevated permissions in order to run any of the cmdlets, just as it requires administrative privilege to do any administration of GPO’s through the GPMC. 

The shortcut to the Active Directory provider is located in the Start Menu, or just search for “Active Directory” from the Run prompt.

2. Import-module grouppolicy –verbose [note: this may be “add-module” in the beta build]

-Verbose allows you to see all of the available GP cmdlets that are available.  You can also get this list via the get-command cmdlet:

Get-command *-GP*

These 25 cmdlets are available on any machine with the Windows Server 2008 R2 GPMC (that includes Windows 7 client machine with the GPMC installed through RSAT). (If this errors, you probably have not added Group Policy as a feature on your server, or you have not installed the GPMC on your client machine). If you don’t want the full printout, just drop the–verbose flag. This import-module line must be present at the start of any PowerShell script using the GP cmdlets and the start of any PowerShell console session. It is not automatically loaded.

3. Set a registry key value using the Group Policy set-GPRegistryValue cmdlet

Here it is, now let’s walk through it

Set-GPRegistryValue -Name <name of gpo> –Key “HKEY_CURRENT_USER\Software\Adobe\Acrobat Reader\8.0\InstallPath” -ValueName "(Default)" -Value "C:\ProgramFiles(x86)\Adobe\Reader8.0\Reader" -Type String

To reference the help for this cmdlet, say : get-help set-GPRegistryValue, or set-GPRegistryValue -? . This will help you understand what is required, what each of the parameters is expecting, and what you are doing.

First up, refer to the GPO by its display name or its GUID with the appropriate parameter (-Name or –GUID).

Set-GPRegistryValue -Name<name of gpo> –Key “HKEY_CURRENT_USER\Software\Adobe\Acrobat Reader\8.0\InstallPath” -ValueName "(Default)" -Value "C:\ProgramFiles(x86)\Adobe\Reader8.0\Reader" -Type String

The rest of the parameters correspond to the fields of regedit.

Key refers to the key name (right-click on the node in the left-hand panel of regedit and select “copy key name”)

ValueName refers to “Name” (first column in the right-hand panel). This is the name of the value you are setting (get it? Value Name = name of the value). If you are setting the (Default) value, this name is either “” or “(Default)”  case insensitive.

Type refers to “Type”.  As in data type. Friendly English words are acceptable here, like “string” instead of “reg_sz”.

Value refers to “Data”.  The value you want to set. You cannot say “enable” or “disable”, you have to use the actual value to be written into the registry. This cmdlet is writing to the registry. This is not a parser, you have to know what you want.

Why the disparity? There are lots of ways to refer to registry values  (registry keys or registry settings or settings or policy settings or…), so we created a nomenclature that would make the most sense.

But once you do it, that’s it: you just set a registry value in a GPO without having to create your own ADMX file.

So here goes, once more for good measure:

Set-GPRegistryValue -Name <name of gpo> –Key “HKEY_CURRENT_USER\Software\Adobe\Acrobat Reader\8.0\InstallPath” -ValueName "(Default)" -Value "C:\ProgramFiles(x86)\Adobe\Reader8.0\Reader" -Type String

Note: For further experimentation, there are some intricacies here with “Remove” , which has a different result than the –Disable flag. This is all explained in the help.

Go! Experiment! Impress your friends and family with your new-found power. Be the PowerShell expert with your Group Policy friends (I dare you).

Lilia Gutnik, Group Policy PM

Check a setting in all GPO's (Security, ADMX, and more)

$
0
0
 

You configured a setting in one GPO and want to know what that setting is across all GPO’s.

 

You want to check that a setting is not being overwritten by another GPO in the same domain (without checking through every settings report).

 

Sound familiar?

 

Well, we’ve heard you. And made something that should help (using the Group Policy PowerShell work in Windows Server 2008 R2). I’ll show you how you can check things like security settings, ADMX settings, Group Policy Preference items, and logon/logoff scripts and return the values across all GPO’s in a domain. Watch for more posts that will show all of these examples.

 

If you’ve read about or used the Group Policy PowerShell cmdlets, you may have come across Get-GPOReport. You can output the report to HTML, (like clicking “Settings” in the GPMC)  or to XML, which is cool. Why?  Because you can use the XML to search for settings in GPO’s, which is what I did in this little script I wrote. It basically searches all the GPOs in a given domain for a specific setting using the XML returned from the Get-GPOReport cmdlet. Be warned, this is just an example of using Get-GPOReport’s XML report to search GPOs; this might not work for all cases (I certainly haven’t tested it thoroughly), and there may be bugs, so take it as is and adapt it for your own usage.  It is also definitely not optimized, if you have many GPOs it could take a while to run. The point here is the potential: take this script and run with it! It's attached to this post (check the 'Attachments' link by clicking on this post's title and scroll to the bottom)

 

This script’s usage is as follows:

 

SearchGPOsForSetting.ps1 [–IsComputerConfiguration] <Boolean> [-Extension] <String> [-Where] <String> [-Is] <String> [[-Return] <String>] [[-DomainName] <String>]

[-Verbose] [-Debug] [-ErrorAction <ActionPreference>] [-WarningAction <ActionPreference>] [-ErrorVariable <String>] [-WarningVariable <String>] [-OutVariable <String>] [-OutBuffer <Int32>]

 

Notes: In order to get all the inputs correct you may have to open up the XML once of a GPO that has the setting you want to search for.  DomainName is an optional parameter (if you do not specify a domain, it will use the domain of the current context).

 

Lets look at some examples!

 

 

Example 1:Security Setting

 

 Say you wanted to look for a security setting in all the GPO’s in your domain (Policies\WindowsSettings\SecuritySettings\AccountPolicies\Account Lockout Policy\Account lockout duration):

 

clip_image002

 

                If you peek at the XML report of this particular GPO you see the following:

 

<ExtensionData>

            <Extensionxmlns:q2="http://www.microsoft.com/GroupPolicy/Settings/Security"xsi:type="q2:SecuritySettings">               

                <q2:Account>

                    <q2:Name>LockoutDuration</q2:Name>

                    <q2:SettingNumber>20</q2:SettingNumber>

                    <q2:Type>Account Lockout</q2:Type>               

                                                </q2:Account>

            </Extension>

</ExtensionData>

 

 

Using the script, enter where the setting is (-isComputerConfiguration $true), what type of setting it is (-Extension Security), and what value you’re looking for (-Where Name –Is LockoutDuration). If you want to know that the setting is configured in the GPO, but you don’t care what the value is, omit the –Return parameter.

 

PS C:\share> .\SearchGPOsForSetting.ps1 -IsComputerConfiguration $true -Extension Security -Where Name -Is LockoutDuration -Return SettingNumber

 

The Gpo 'simpleGpo' has a Security setting where 'Name' is equal to 'LockoutDuration' and the value of its 'SettingNumber' property is: '30'

The Gpo 'securityGpo' has a Security setting where 'Name' is equal to 'LockoutDuration' and the value of its 'SettingNumber' property is: '20'

 

 

 

Example 2: ADMX setting

 

clip_image004

 

      Looking at the xml:

 

<ExtensionData>

            <Extensionxmlns:q4="http://www.microsoft.com/GroupPolicy/Settings/Registry"xsi:type="q4:RegistrySettings">

                <q4:Policy>

                    <q4:Name>Turn off Windows Startup Sound</q4:Name>

                    <q4:State>Enabled</q4:State>

                    <q4:Explain>

                        Turn off the Windows Startup sound and prevent its customization in the Sound item of Control Panel.

                        The Microsoft Windows Startup sound is heard during system startup and cold startup and can be turned on or off in the

                        Sound item of Control Panel.

                        … /more xml

 

Then you would run this script in the following way:

 

    

  PS C:\share> .\SearchGPOsForSetting.ps1 -IsComputerConfiguration $true -Extension Registry -Where Name -Is "Turn off Windows Startup Sound" -Return State

 

The Gpo 'simpleGpo' has a Registry setting where 'Name' is equal to 'Turn off Windows Startup Sound' and the value of its 'State' property is: 'Enabled'

The Gpo 'gpoB' has a Registry setting where 'Name' is equal to 'Turn off Windows Startup Sound' and the value of its 'State' property is: 'Disabled'

 

 

More examples to come, let me know what you think so far!

 

 Lindsay Harris, Group Policy Software Developer

 

     

 


Check a setting in all GPO's continued (scripts, firewall, GP Preferences and more)

$
0
0

 I mentioned this in the last post, here are some more examples.  To download the script, check the 'Attachments' link by clicking on this post's title and then scrolling to the bottom. Quick refresher:

 

This script’s usage is as follows:

 

SearchGPOsForSetting.ps1 [–IsComputerConfiguration] <Boolean> [-Extension] <String> [-Where] <String> [-Is] <String> [[-Return] <String>] [[-DomainName] <String>]

[-Verbose] [-Debug] [-ErrorAction <ActionPreference>] [-WarningAction <ActionPreference>] [-ErrorVariable <String>] [-WarningVariable <String>] [-OutVariable <String>] [-OutBuffer <Int32>]

 

Notes: In order to get all the inputs correct you may have to open up the XML once of a GPO that has the setting you want to search for.  DomainName is an optional parameter (if you do not specify a domain, it will use the domain of the current context).

 

 

Lets look at some more examples!

 

 

Example 3: Are there any logon scripts?

 

If you just want to find the GPOs in your domain that have a specific logon script, you can omit the -Return parameter

     

clip_image006

 

<ExtensionData>

<Extension xmlns:q5="http://www.microsoft.com/GroupPolicy/Settings/Scripts" xsi:type="q5:Scripts">

<q5:Script>

           <q5:Command>\\myserver\myshare\myLogonScript.ps1</q5:Command>

           <q5:Type>Logon</q5:Type>

            <q5:Order>0</q5:Order>

           <q5:RunOrder>PSNotConfigured</q5:RunOrder>

</q5:Script>

</Extension>

<Name>Scripts</Name>

       </ExtensionData>

 

              

    PS C:\share> .\SearchGPOsForSetting.ps1 -IsComputerConfiguration $false -Extension Scripts -Where Command -Is \\myserver\myshare\myLogonScript.ps1

 

  The Gpo 'simpleGpo' has a Scripts setting where 'Command' is equal to '\\myserver\myshare\myLogonScript.ps1'

 

 

Example 4:  Group Policy Preferences

 

clip_image008 

 

               

If I wanted to see all my URL shortcuts in User policy:

 

<ExtensionData>

<Extension xmlns:q5="http://www.microsoft.com/GroupPolicy/Settings/Shortcuts" xsi:type="q5:ShortcutSettings">

<q5:ShortcutSettings clsid="{872ECB34-B2EC-401b-A585-D32574AA90EE}">

<q5:Shortcut clsid="{4F2F7C55-2790-433e-8127-0739D1CFA327}" userContext="1" name="MS" status="MS" image="0" changed="2009-04-10 21:39:08" uid="{8D545947-9080-446D-A5C8-8E447407C7AF}">

<q5:GPOSettingOrder>1</q5:GPOSettingOrder>

<q5:Propertiespidl=""targetType="URL" action="C" comment="" shortcutKey="0" startIn="" arguments="" iconIndex="13"targetPath="http://www.microsoft.com/" iconPath="%SystemRoot%\system32\SHELL32.dll" window="" shortcutPath="%DesktopDir%\MS" />

<q5:Filters/>

</q5:Shortcut>

</q5:ShortcutSettings>

</Extension>

<Name>Shortcuts</Name>

</ExtensionData>

 

 

PS C:\share> .\SearchGPOsForSetting.ps1 -IsComputerConfiguration $false -Extension Shortcuts -Where targetType -Is URL -Return targetPath

 

The Gpo 'simpleGpo' has a Shortcuts setting where 'targetType' is equal to 'URL' and the value of its 'targetPath' property is: 'http://live.com'

The Gpo 'gpoB' has a Shortcuts setting where 'targetType' is equal to 'URL' and the value of its 'targetPath' property is: 'http://www.microsoft.com'

The Gpo 'gpoA' has a Shortcuts setting where 'targetType' is equal to 'URL' and the value of its 'targetPath' property is: 'http://www.msdn.com'

 

 

 

 

Example 5:  Find all the open firewall ports

               

<ExtensionData>

<Extension xmlns:q2="http://www.microsoft.com/GroupPolicy/Settings/WindowsFirewall" xsi:type="q2:WindowsFirewallSettings">

<q2:GlobalSettings>

<q2:PolicyVersion>

<q2:Value>522</q2:Value>

</q2:PolicyVersion>

</q2:GlobalSettings>

<q2:InboundFirewallRules>

<q2:Version>2.10</q2:Version>

<q2:Action>Allow</q2:Action>

<q2:Name>open port 448</q2:Name>

<q2:Dir>In</q2:Dir>

<q2:LPort>448</q2:LPort>

<q2:Protocol>6</q2:Protocol>

<q2:Active>true</q2:Active>

</q2:InboundFirewallRules>

</Extension>

<Name>Windows Firewall</Name>

</ExtensionData>

 

    

PS C:\share> .\SearchGPOsForSetting.ps1 -IsComputerConfiguration $true -Extension WindowsFireWall -Where Action -Is Allow -Return LPort

 

The Gpo 'gpoA' has a WindowsFireWall setting where 'Action' is equal to 'Allow' and the value of its 'LPort' property is: '448'

The Gpo 'gpoB' has a WindowsFireWall setting where 'Action' is equal to 'Allow' and the value of its 'LPort' property is: '80'

 

 

 Note: Under the hood I am using XPath and XmlNamespaceManager, to find the xml for the Specific extension you passed in and then I perform a recursive search of the xml underneath that for the Property you specified with $Where that has the value you specified with $Is.  Then, once it finds that, if you specified a $Return parameter it will search for that property to return the value it has. 

 

I hope you enjoy working with this script. Let me know what other interesting and compelling scenarios you use this for in the comment section. Also, if you re-work it to fit your own need, post it back here and explain what you did and why. 

 

Can't wait to see what you come up with, 

 Lindsay Harris, Group Policy Software Developer

PowerShell Script with GP cmdlets: Registry setting, Link

$
0
0

 The following is a sample script that sets a Preference registry value in a GPO, then compares that same value to all of the GPO's linked in the same domain. If the value is not already set in a linked GPO, the new GPO is linked to that domain as well.

You can copy and paste the following text into a .ps1 file and run it, given a few modifications (the comments denote where you should replace my example names with your own GPO and domain names). The # symbols act like comments in the .ps1 file so you don't need to worry about them being run or printing out.

Hope this helps!

 LiliaG, Group Policy PM

 

## The following script sets a Preference registry value in a GPO, then compares that same value to all of the GPO's linked in the same domain
## it depends on being opened from the Active Directory provider shortcut to the PowerShell console, or navigating to that AD provider first

# necessary for any work with group policy cmdlets
import-module grouppolicy

# create new GPO. Replace "GPDEMO" with the name of your choice

new-GPO GPDEMO

# set the variable $key to the string value of the registry key to be set

$key = 'HKEY_CURRENT_USER\Software\Adobe\Acrobat Reader\8.0\InstallPath'

# set GP Pref Registry Value

Set-GPPrefRegistryValue -Name GPDEMO -Context User -Key $key -ValueName (Default) -Value "C:\ProgramFiles(x86)\Adobe\Reader8.0\Reader" -Type String -Action Create

#get all GPO's linked in the domain you choose
#first step is to get the domain object you want

#Replace <your domain here> with the NetBIOS, DNS, SID, or Distinguished Name of the domain

$domain = get-ADDomain -Identity <your domain here>

# enter "get-ADDomain -?" for help

# the next step gets all the GPO's currently linked to that domain and extends the attributes to include the GUID of those GPO's

# the second portion of this line is important for parsing the resulting list of GPOs, do not skip it! You must get the " -properties Name " in order to refer to the GPO's by their GUID.

$GPOList = $domain.AppliedGroupPolicies | %{Get-ADObject $_ -Properties Name}

# sets up the variable to be compared against the other GPO's in the domain

$preference = get-GPPrefRegistryValue -Name GPDEMO -Context User -Key $key -ValueName (Default)

# warning: this does not check to see if there are other GPO's linked to the domain, this loop will break if there is only one GPO linked in the domain

# loop through

$i = 0
$redundantSetting = 0

while ($i -lt $GPOList.count) {

$CompareGPO = get-GPO -GUID $GPOList[$i].Name

# report out equality

if (($preference.Value).equals($comparePref.Value))
  {
    "Equal!"
     $redundantSetting++
  } else {
     "Not Equal!"
  }

# reset the loop

$comparePref = 0
$i++
}

# if none of the GPO's linked to the domain have the setting, link this new GPO. Otherwise, do not link it.

if ($redundantSetting -gt 0)
  {
     new-GPLink GPDEMO -Target $domain
  } else {
    "Not linking a redundant GPO"
  }

Now, when I detect a redundant setting, I just print something out to the screen. You can do something more interesting, like write to a file, trigger another script, send an email, etc. In fact, I hope you do! Let me know what you do with this script, how you improve it, if/how you use it, or if it causes you any trouble.

Microsoft Management Summit 2009

$
0
0

I just got back from another great MMS in Las Vegas and I’d like to thank everyone who stopped by the booth, attended the Group Policy-related sessions, and asked great questions about Group Policy and AGPM (thanks to Chris for Tweeting about it!). I’m so glad to see that more and more people are using Group Policy Preferences.

Are you using Group Policy Preferences in your environment? Do you have an interesting example of targetting? A great drive mapping? Post your examples in the comments. (just copy and paste the relevant XML and/ or describe what you did)

For those of you who are curious about the specific blog posts I mentioned with script samples, here they are:

Drive Mapping with GP Preferences

Find any setting in every GPO (part 1, part 2) (PowerShell script)

Set a registry key (PowerShell cmdlet)

Backup all GPO’s modified in the last month (PowerShell script)

Troubleshooting using the Event Viewer

TechEd is right around the corner and we Group Policy folks will be there to keep talking about these topics, answer questions, and be our charming Group Policy selves. Come say hi to Michael, and be sure to ask him about his New Zealand accent.

LiliaG, Group Policy PM

Group Policy at Tech Ed 2009 keynote: Mark Russinovich demos Group Policy PowerShell cmdlets

$
0
0

During this morning’s keynote at TechEd 2009 in Los Angeles, technical fellow Mark Russinovich demonstrated the Set-GPRegistryValue cmdlet. He points out the power of scripting; a few lines created a GPO, configured a registry value, and linked it to an OU. A few changes would link that same GPO to any number of OUs, domains, etc.

When it's up, I'll post it. Group Policy in the keynote!

[EDITED] Watch it here : http://www.msteched.com/online/view.aspx?tid=6fc7b7da-2d2d-4e57-9acf-cf77890a1738 

If that link is troublesome for you, navigate to the 'keynote' talk from here: http://www.msteched.com/online/home.aspx

Watch it at the 52 minute mark until 56 minutes for the Group Policy - PowerShell bit, where he demos configuring IE8 specific settings using the Set-GPRegistryValue and New-GPLink. He talks about AppLocker beforehand, which is pretty interesting as well. There's a lot of great content in this keynote, I'm glad that Group Policy was included.

LiliaG, Group Policy PM

Cool Articles: Group Policy Modeling, Windows 7 / Server 2008 R2 functionality

$
0
0

I just read a couple of great articles written in the past couple months about Group Policy. Ever wondered which policy is going to 'win' on a client with overlapping settings from different GPOs? Want to know more about Starter GPO's or Preferences? Read on...

 

The first one walks through how to diagnose hierarchy issues by using the Group Policy Modeling tools that are part of the GPMC.

 

“…you can see various policies and their corresponding settings listed. The "winning" GPO column tells you which Group Policy Object is responsible for applying those settings. Keep in mind that this will not always be the highest GPO in the hierarchy. It might list a lower-level Group Policy Object if it applies a setting and none of the higher-level policies address that particular setting.”

 

You can read it here, though you have to register to read the full article (but it’s free, so just fill out the form and be done with it): Group Policy Object modeling simplified network security. (Written by Brien Posey)

 

The second one is on the same site (One registration! Two articles!) . It discusses the new Server 2008 R2/ Windows 7 functionality including some detail around how to create Group Policy Preference Items and why they are great (the reasons are obvious, of course). He also gives some good background about Group Policy, Starter GPO’s, and the PowerShell cmdlets.

 

 Group Policy makes strides in Windows Server 2008 R2.(Written by Jonathan Hassell)

 

Hope you enjoy them!

 LiliaG, Group Policy PM

How long does this script / WMI Filter take?

$
0
0

I was reading GP MVP Darren Mar-Elia’s forum about WMI Filters and discovered a sweet PowerShell trick from another awesome friend of the GP team, Thorbjörn Sjövold (CTO of Specops Software)

You can use the PowerShell cmdlet “measure-command” to measure the time it takes to run script blocks and cmdlets – this includes WMI filters! This came up in a thread about logon time.

Read the full thread here.

Here's how to set it up"...deploy a new environment variable, for example INSTALLADOBE using Group Policy Preferences. Use their Windows Installer Target and then use a WMI filter like this for the actual installation.

 SELECT * FROM Win32_Environment WHERE Name = 'INSTALLADOBE'


You can compare the two WMI queries like this using PowerShell to get an idea on how much faster it is:


measure-Command {Get-WmiObject -query "SELECT * FROM Win32_Environment WHERE Name = 'OS'"}


just substitute the OS name with the name of any Environment variable like INSTALLADOBE, but to test the speed it does not really matter. 

measure-command {Get-WmiObject -query "Select * from Win32_Product where Name like '%Adobe Reader%'"}

"

Thanks guys! Hope you find this useful,

@superlilia

Group Policy & Scripting


More powershell & group policy

$
0
0

I do not know about you but I LOVE PowerShell, especially the Group Policy cmdlets. Unfortunately, I didn’t have too many opportunities to really use them - but luckily got a chance in preparation for a presentation where I would demo a script that Lindsay (from our dev team) put together.

This script allows you to find any Group Policy setting across all of your GPOs in your domain. Lindsay outlines how to use her script in the following blog posts:

Video on TechnetEdge: Searching for settings in a GPO

Checking a setting in all GPO’s (Security ADMX, and more)

Checking a setting in all GPO’s continued (scripts, firewall, GP Preferences and more)

In preparing, however, I encountered something that many of you have already run into: The suspicious lack of a get cmdlet for GPlinks.  Executing the get-help *-GPLink* command in a PowerShell window with the GP cmdlets loaded returns the following:

Name                                                    Category                              Synopsis
--------                                                   ------------                            ------------
New-GPLink                                       Cmdlet                                 Links a GPO to a site, domain, o…
Remove-GPLink                                  Cmdlet                                 Removes a GPO link from a site, …
Set-GPLink                                          Cmdlet                                 Sets the properties of the speci…

Where is the Get-GPLink? It does not exist. Well at least it is not included as one of Microsoft’s cmdlets. I have found that a PowerShell function was created by Jeff Hicks in an attempt to fill the void. For my demo, however, I wanted a built-in solution.

After some digging and experimenting, I found a simple way to determine what containers a GPO is linked to and it can be done with only 3 lines of PowerShell script. I used the Active Directory get-ADObject cmdlet combined with the Filter parameter. The filter parameter allows me to use PowerShell Expression language to query AD for the object that I am looking for. The specific thing that I am looking for is any object that has the gPLink property which contains the GUID for the GPO I am interested in.

To do that I first need to get the GUID for the GPO I am interested in:

1.       $myGPO = Get-GPO –name {display name of GPO}

2.       $myGPOID = “*” + $myGPO.Id + “*”

Then I pass that into the get-ADObject cmdlet to get the FQDNs for all containers that the GPO is attached to:

3.       $Path = get-ADObject –Filter {gPLink –Like $myGPOID}

And as simple as that, I have all containers stored in the variable $Path that a specific GPO is linked to.

MarkG

More on searching group policy

$
0
0

Here’s a quick follow-up to our last post on the existence of GPO search. One of our MVPs, Alan, has a great post up about a Group Policy Search webapp (Previously mentioned on this blog). It includes instructions on how to install a Windows Search connector – so you can use this search right from Windows Explorer!

 

Someone noted that you can't search for comments in the GPMC search. Very true! However, by using the "Description" property exposed by Group Policy cmdlets in Powershell, we might be able to make something work…

 

This script searches for policies with comments and displays them:

 

 

import-module grouppolicy; #use group policy cmdlet

$arrPolicy = get-gpo –all; #get all GPOs and store them in an array

$arrCommented = @(); #create an empty array for GPOs matching our criteria (in this case, commented GPOs)

Foreach($GPO in $arrPolicy) {

 If ($GPO.Description) { $arrCommented += $GPO; } #if it has a comment, add it to the array

}

Write-output (format-list –property DisplayName, Description –inputobject $arrCommented); #Make it look pretty and then print it

 

This script searches for policies with comments and displays them. In Powershell, you can test for the existence of a property with  if($property) and the non-existence of a property  if(!$property). (These statements can also be understood as:

 if ($property -eq $NULL) and if($property –ne $NULL)

respectively.  Just one of the many shortcuts Powershell provides!)

Once you have this up and running, you can try a few other things. Want to search for a specific substring within the comments? Replace the if-statement above with these two lines:

If ($GPO.Description)

{ if ( $GPO.Description.contains(“foo”) ) {$arrCommented += $GPO; } }

The first if-statement is still checking for existence, so the second if-statement can be assured the description exists – and look through it for any specific string.

Of course, this script probably could be reduced down to a few lines. If anyone wants to go golfing with this script, post your best entry in the comments!

Copy and Merge GPOs through Powershell

$
0
0

Ashley McGlone has a great script up for merging GPOs together through powershell.

I wish I had this script five years ago. At the time I was searching for a way to combine or merge GPOs, but there simply wasn’t a way to do it. And today there still isn’t a way to do it… until POWERSHELL! Almost every environment I see (including my own former environment) has a collection of GPOs that have evolved over time and really need to be consolidated and cleaned up.

In Windows Server 2008 R2 we released a new PowerShell module for Group Policy administration. I haven’t seen much written about it, and I don’t think many people realize it is there.

Check it out!

Get GPO Backup with Powershell

$
0
0

Jeff Hicks, one of Microsoft’s Powershell MVPs, has written a great script for managing GPO backups:

The GroupPolicy module from Microsoft offers a great deal of functionality from a command line. In terms of regular maintenance or administration it is pretty hard to beat, especially if you have 100s or 1000s of GPOs. When you have such a large number, backing them up is critical and easy to accomplish with the Backup-GPO cmdlet. However, if you want to restore or import from a backup, you have to resort to the graphical Group Policy Managment Console. I couldn’t find any way to manage GPO backups from PowerShell so I wrote my own.

 

It also has explanations for how the script functions, and how to use it. The download link is at the bottom of his post.

RSAT & GP Cmdlets

$
0
0

This post was written by Judith, a technical writer for Group Policy. This will be the first post in a series on ways to use Powershell with Group Policy

I wanted to play around with the Group Policy cmdlets. These are installed on Windows Server 2008 R2 automatically when Group Policy is installed. But what I really wanted to do was use them on my Windows 7 client machine where I do most of my Group Policy administration.

I installed RSAT (Remote Server Administration Tools) for Windows 7, I now had access to the Group Policy cmdlets on my Windows 7 client.

So, instead of having to remote into my Windows Server 2008 R2 server directly or try to use the remoting built into Windows PowerShell, I can install RSAT and then use the GP cmdlets in the same way I would on Server 2008 R2.

Once RSAT is installed, I can open a Windows PowerShell command window and find out the Windows PowerShell modules that I can use with the command get-module -listavailable

PS C:\> get-module -listavailable ModuleType Name ExportedCommands ------------------------------ Manifest ActiveDirectory {} Manifest AppLocker {} Manifest BitsTransfer {} Manifest GroupPolicy {} Manifest PSDiagnostics {} Manifest TroubleshootingPack {}

Then I can import the Group Policy module to make all the GP cmdlets available within my Windows PowerShell window with the command import-module GroupPolicy 

And a scripting we will go…

Viewing all 56 articles
Browse latest View live


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