Hello,
Sure, find the updated script below:
$fileName = "%username%" # TODO: modify me
$filePathTemplate = "\\OURSERVER\D$\Group Membership Files\{0}.txt" # TODO: modify me
# Check Primary Group
$primaryGroupId = $Context.TargetObject.Get("primaryGroupID")
if ($primaryGroupId -ne 513)
{
# Add user to Domain users group
$domainName = $Context.GetObjectDomain("%distinguishedName%")
$domain = $Context.BindToObject("Adaxes://$domainName")
$domainSidBytes = $domain.Get("objectSid")
$domainSid = New-Object "System.Security.Principal.SecurityIdentifier" `
@($domainSidBytes, 0)
$domainUsersGroupSid = New-Object "System.Security.Principal.SecurityIdentifier" `
@([System.Security.Principal.WellKnownSidType]::AccountDomainUsersSid, $domainSid)
$domainUsersGroup = $Context.BindToObject("Adaxes://<SID=$domainUsersGroupSid>")
try
{
$domainUsersGroup.Add($Context.TargetObject.AdsPath)
}
catch [System.Runtime.InteropServices.COMException]
{
if ($_.Exception.ErrorCode -ne 0x80071392)
{
$Context.LogMessage("An error occured when adding user to 'Domain users' group. Error: " + $_.Exception.Message, "Warning")
return
}
}
# Set Domain users as primary group
$Context.TargetObject.Put("primaryGroupID", 513)
$Context.TargetObject.SetInfo()
}
# Get all groups user is a direct member of
$groupGuids = $Context.TargetObject.GetEx("adm-DirectMemberOfGuid")
# Create a plain text report
$report = New-Object "System.Text.StringBuilder"
$report.Append("The user was removed from the following groups:")
foreach ($groupGuidBytes in $groupGuids)
{
# Bind to the group
$groupGuid = New-Object "System.Guid" (,$groupGuidBytes)
$groupGuid = $groupGuid.ToString("B")
$groupPath = "Adaxes://<GUID=$groupGuid>"
$group = $Context.BindToObject($groupPath)
# Skip the group if it is the user's Primary Group
if ($group.Get("primaryGroupToken") -eq 513)
{
continue
}
# Remove user from the group
$group.Remove($Context.TargetObject.AdsPath)
# Add the group to the report
$report.AppendLine()
$report.Append($group.Get("name"))
}
# Create a new text
$filePath = [System.String]::Format($filePathTemplate, $fileName)
if (-not (Test-Path -Path $filePath))
{
$file = New-Item -Path $filePath -ItemType File
}
else
{
# Create unique name for file
for ($i = 1; $True; $i++)
{
$uniquefileName = $fileName + $i
$filePath = [System.String]::Format($filePathTemplate, $uniquefileName)
if (Test-Path -Path $filePath)
{
continue
}
break
}
$file = New-Item -Path $filePath -ItemType File
}
# Save the report to the file
Add-Content $file $report.ToString()