Tuesday, February 12, 2008

Group Policy Objects and Powershell - 2 Creating the GPOs

As was quickly pointed out to me SDM Software has some excellent freeware Cmdlets available, and if you don't know this is Darren Mar-Elia's – The GPO Guy's company and so they are no doubt well written and will do the job for you. Having said that, it wasn't an option for me as the Company I work for would never have accepted me using them, and I would have felt bad using someone else's work in large AD implementations. More importantly this gave me a chance at playing around with Powershell, and achieve something useful with it. So I would say if Darren's cmdlets do the job for you and you are happy using them, then make use of them, if not then read on.

After you look at the completed scripts if you are familiar with the wsf scripts you get with GPMC then you will begin to see the similarities and it will make it easier to come up with your own Powershell scripts.

As previously mentioned the Technet article - Simplify Group Policy Administration with Windows PowerShell
is a good introduction and explains that the wsf GPMC scripts actually call the GPMgmt.GPM COM object, and as COM objects can be called directly from Powershell we can work with this to do most of, if not all we need to do with Group Policy objects (with the exception of amending contents of the GPO itself).

So the first thing we need to do in this script is to define the domain we are going to work with and the name of the GPO we want to create, then instantiate the COM object, Connect to the Domain, then create the GPO with the Display name you defined earlier.

$domainName="Philtest.PRI"

$gpmName="GPO 1"

$gpm = New-Object -ComObject GPMgmt.GPM

$gpmConstants = $gpm.GetConstants()

$gpmDomain = $gpm.GetDomain("$domainName", "", $gpmConstants.UseAnyDC)

$gpmGpo = $gpmDomain.CreateGPO()

$gpmGpo.DisplayName = "$gpmName"


So this is a useful way of starting the script, but what if you want to create a number of GPOs defined in a text file? Actually it is pretty straight forward you can create a text file that lists the GPOs on separate lines:-

GPO 1

GPO 2

GPO 3

GPO4

So from here you need to add some elements to the script to connect to this text file and retrieve the GPO names:-


$aryText = Get-Content -Path "c:\PSScripts\GPOs.txt"

forEach ($aryElement in $aryText)

{

$gpm = New-Object -ComObject GPMgmt.GPM

$gpmConstants = $gpm.GetConstants()

$gpmDomain = $gpm.GetDomain("$domainName", "", $gpmConstants.UseAnyDC)

$gpmGpo = $gpmDomain.CreateGPO()

$gpmGpo.DisplayName = $aryElement

}


This script gets the contents of the text file and scrolls through it creating GPOs with the Displaynames of Whatever is on each line of the text file(in the case GPO 1, GPO 2, GPO 3, GPO 4)

No comments: