Script Repository


Current group membership of a user

August 17, 2021
97

The script sends an email with a list of groups the target user is a member of attached as a CSV file. To execute the script, create a custom command, business rule or scheduled task configured for the User object type.

Parameters:

  • $csvFilePath - Specifies the path to the CSV file that will be temporarily created.
  • $removeCSVFile - Specifies whether to remove the CSV file after sending email.
  • $propertyNameToColumn - Maps LDAP names of properties with the names of the corresponding columns that will be present in the CSV file.
  • $to - Specifies the email notification recipients.
  • $from - Specifies the address from which the email notification will be sent.
  • $smtpServer - Specifies the SMTP server that will be used to send the email notification.
  • $subject - Specifies the email notification subject.
  • $message - Specifies the email notification text.
Edit Remove
PowerShell
$csvFilePath = "d:\Dracula\Support\Groups.csv"  # TODO: Modify me
$removeCSVFile = $True # TODO: modify me
$propertyNameToColumn = @{
    "Name" = "Name";
    "Description" = "Group description"
} # TODO: modify me. $propertyNameToColumn = @{"<ldap property name>" = "Column name"}

# Mail settings
$to = "recipient@domain.com", "recipient2@domain.com" # TODO: modify me
$from = "noreply@localhost" # TODO: modify me
$smtpServer = "smtpserver.domain.com" # TODO: modify me
$subject = "My subject" # TODO: modify me
$message = "My message" # TODO: modify me

# Get GUIDs of groups user is a member of
$groupGuidsBytes = $Context.TargetObject.GetEx("adm-DirectMemberOfGuid")

# Get group names
$searcher = $Context.CreateGuidBasedSearcher($groupGuidsBytes)
try
{
    $searchResultIterator = $searcher.ExecuteSearch()
    $searchResults = $searchResultIterator.FetchAll()
    
    $records = New-Object System.Collections.ArrayList
    foreach ($searchResult in $searchResults)
    {
        $recordProperties = @{}
        foreach ($propertyName in $propertyNameToColumn.Keys)
        {
            $value = $searchResult.Properties[$propertyName].Value
            $recordProperties.Add($propertyNameToColumn[$propertyName], $value)
        }
        
        $record = New-Object PSObject -Property $recordProperties
        $records.Add($record)
    }
    
}
finally
{
    # Release resources
    if ($searchResultIterator){ $searchResultIterator.Dispose() }
}

$records.ToArray() | Export-Csv -Path $csvFilePath -NoTypeInformation

# Send mail
Send-MailMessage -To $to -from $from -SmtpServer $smtpServer -Subject $subject -Body $message -Attachments @($csvFilePath)

if ($removeCSVFile)
{
    # Remove the file
    Remove-Item -Path $csvFilePath -Force
}


Comments ( 0 )
No results found.
Leave a comment

Related Scripts