This is the 2nd in an irregular series of discussions about using SDM Software PowerShell cmdlets for managing Group Policy. In this post, I’ve written a fairly simple PowerShell script that uses two of our free GPMC cmdlets to first backup a GPO, and then launch the GP Editor on that GPO. This can be a useful way to edit GPOs because it guarantees that before you make any changes to that GPO, that you have a backup copy. This script uses two of our GPMC cmdlets–namely export-sdmgpo and get-sdmgpo. The Export cmdlet backs up the gpo that you specify and then get-sdmgpo grabs the GUID for that GPO, which needs to be passed to gpedit.msc command in order to launch the GP Editor. Well, let’s look at the script now. I named the script backupAndEdit.ps1 (I know, very original). When I call the script from PowerShell, I pass it 3 parameters, like this:
PS> .backupandedit.ps1 "ADM Test" "\sdm1gpbackups" "Backup and Edit Test"
The first param is the name of the GPO, in this case, its called "ADM Test". The 2nd parameter is the path to my GPO backups. The 3rd param is a comment that is associated with the backup. Obviously you could get more creative here! Now here’s the script:
*****
param($GPOName,$backupLocation,$comment)
write-host "Backing up GPO: $GPOName"
trap {
‘Backup Failed!’
$_
exit
}
export-sdmGPO $GPOName -Location $backupLocation -Description $comment -ea 1
write-host "Backup Completed"
write-host "Launching GP Editor"
$GPO= get-sdmGPO $GPOName
$extcmd = " /gpobject:`"LDAP://CN=" + $GPO.ID + ",CN=Policies,CN=System,DC=cpandl,DC=com`""
gpedit.msc $extcmd
*******
This script is pretty simple. I declare my parameter names at the beginning of the script. Then I set up a trap to catch for any errors during backup–I don’t want to edit the GPO if the backup fails. Then I call export-SDMgpo using the params I passed in. Then assuming the backup completes and the script continues, I use get-sdmgpo to get a reference to the GPO, because from that object I can get the GPO’s GUID (the ID property). Then I assign the full command I want to, including the DN of the GPO, to $extcmd. Finally, I call the external MMC tool gpedit.msc and pass it that arguments in $extcmd. Now, you’ll notice that my domain name is hard-coded into the path here. I could just as easily have passed this in as a parameter as well, or used some AD code to grab my current DN. Just know that if you use this script, you’ll need to modify the command for your own domain name.
Enjoy!
Tags: