List Active Directory group members

A while back, a colleague had the daunting task to create an overview of the membership of some groups in our Active Directory.

At that time, I couldn’t help him off the cuff, but I saw it as a good occasion to delve a bit into Microsoft’s PowerShell scripting language. While I was busy reading about it and testing the script, my colleague finished his task with a lot of mouse-movement and keyboard-typing — maybe next time…

Verdict so far: Not a real fan of the language yet, but it seems to be a powerful tool in a Microsoft environment (and working on the script was a better way to kill some time today than the alternative options… ;-)). But the syntax: Seriously, hyphens?!

Anyways, the main reason for this posting is not the great code, but rather to test some syntax highlighting plug-ins and tagging for WordPress; while keeping that in mind, on with the show code…

The script lists members of an AD group and writes the result to a CSV file.

Requirements:

And here’s the script:

# ------------------------------------------------------------------------------
# Usage:
# -group name : [Mandatory] Name of the AD group.
# -out path   : [Optional] Path for output file.
#               Without this, the file will be saved in the current working directory of the script.
# -recursive  : [Optional] If set, recursion is 'on', the default is 'off'.
# ------------------------------------------------------------------------------

# set-executionpolicy Unrestricted
# set-executionpolicy RemoteSigned 

# The Param() block must be at the beginning of the script!
[CmdletBinding()]
Param
(
    [Parameter(Mandatory=$true)] [string] $group,
    [string] $out,
    [switch] $recursive
)

$OutputFile = ($group + ".csv")

Import-Module ActiveDirectory

if ($recursive) { $Parameters = @{'-Recursive' = $true } }
else            { $Parameters = @{'-Recursive' = $false} }

if ($out)
{
    if (Test-Path $out) { $OutputFile = $out + "\" + $OutputFile }
    else                { Write-Host "`nWarning: Folder $out does not exist! Using default path!" }
}

if (Get-ADGroup -Filter {SamAccountName -eq $group})
{
    Get-ADGroupMember $group @Parameters | select name, samaccountname | Export-Csv $OutputFile
    Write-Host "`nSaved to $OutputFile."
}
else
{
    Write-Host "`nError: Group $group does not exist!"
}

Write-Host "`n"
exit