'Powershell script not calling function

I have modified the following script and adapted it to our needs. All is working as expected but the call to the AppendLog in the TRY.

The log file gets created but it remains empty even after the script ran.

I have a thought that as the script is not removing any membership it wouldn't send an output to the log. But there are users that have DL's on them that can't be removed.

This is the code. Thank you!

function AppendLog ([string]$Message)
    {
        $CurrentAction = $Message
        $TraceLog += ((Get-Date).ToString() + "`t" + $Message + " `r`n")
    }



$path = "OU=Tango,OU=People,DC=Lab,DC=Dev";

Get-ADUser -Filter * -SearchBase $path -Properties memberof| Select DistinguishedName, @{n='memberOf';e={$_.memberOf -join '; '}} | export-csv 'd:/Remove AD Membership/usersbeforescript.csv' -NoTypeInformation

$ExceptGroup = "Domain Users";
$users = Get-ADUser -SearchBase $path -Filter *

foreach ($user in $users) {
        try {
            $UserDN = $user.DistinguishedName
            Get-ADGroup -LDAPFilter "(member=$UserDN)" | foreach-object {
                if ($_.name -ne $ExceptGroup) {
                    Remove-ADGroupMember -identity $_.name -Member $UserDN -confirm:$false
        }
            AppendLog “Removed from $user”
                }
         }catch {
                     AppendLog ”Failed to remove from $user”
                     }
    
    }


$datestring = get-date -format mmddyy
$logfile = ‘D:\Logs\Remove AD Membership\logfile_’ + $datestring + ‘.log’
$tracelog | out-file $logfile

Get-ADUser -Filter * -SearchBase $path -Properties memberof| Select DistinguishedName, @{n='memberOf';e={$_.memberOf -join '; '}} | export-csv 'D:\Remove AD Membership\usersafterscript.csv' -NoTypeInformation




Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source