alex hunt
alex hunt

Reputation: 47

Email Notification on Upon User Attributes update

im currently working on a automated User Attributes updating scrips, and currently that working fine, i am having issues however collecting the list of changes so they can be bundled inot an email notification for the administrator here is what i have so far,

i want to form a list of all changes so that i can add that to an send-mailmessage to an admin for each user, but only when there is a change. at the moment i only get whatever the latest thing changed is, not a list.


$csvFile = 'C:path.csv'  # Enter a path to your import CSV file
$validUsernameFormat = '[^a-zA-Z_.]'                # identifies anything that's _not_ a-z or underscore or .
$Mailpassword = ConvertTo-SecureString -string “4a1fd5e9f7e26f” -AsPlainText -Force
$MailCred = New-Object System.Management.Automation.PSCredential -argumentlist "38da1ca9daf082", $Mailpassword
$mailBody = $NewUserParams | out-string



# read the input csv and loop through
Import-Csv -Path $csvFile | ForEach-Object {
    $firstName = $_.FirstName.Trim()
    $surname = $_.Surname.Trim()
    #$validUsernameFormat = "[^a-zA-Z_.]"                                        # identifies anything that's _not_ a-z or underscore or .
    $vaildusername = "($firstName'.'$surname)" -replace $validUsernameFormat, ''       #removes anything that isn'tin $validUsernameFormat
    $truncateifgreaterthanXchar = '(?<=^.{20}).*'
    $username = $vaildusername -replace $truncateifgreaterthanXchar
    $DefaultPassword = 'Pa$$w0rd'
    $securePassword = ConvertTo-SecureString -String $DefaultPassword -AsPlainText -Force



    # test if a user with that name already exists
    $user = Get-ADUser -Filter "SamAccountName -eq '$username'" -ErrorAction SilentlyContinue
    if ($user) {
        $CurrentAttributes = Get-ADUser -Identity $username -Properties *
        # You don't need this line because you are already declaring the variable in the next one
        # [psobject]$CorrectAttributes
        $CorrectAttributes = @{
            SamAccountName    = $username
            Name              = "$firstname $surname"
            DisplayName       = "$firstname $surname"
            UserPrincipalName = "[email protected]"
            GivenName         = $firstname
            Surname           = $surname
            Path              = "CN=Users,DC=domain,DC=com" #change to switch based of Users Branch
            City              = $_.City
            Country           = $_.Country #NOTE: This Feild must be the 2 digit Country Code, NOT the String Name of athe Country.
            department        = $_.OrgDepartmentName
            Employeeid        = $_.EmployeeId
            mobile            = $_.Mobile
            Manager           = $_.Manager
            Office            = $_.Branch
            postalCode        = $_.PostalCode
            POBox             = $_.PostOfficeBox
            scriptPath        = $_.scriptPath
            Street            = $_.StreetName
            Title             = $_.Title
        }
        [System.Collections.ArrayList]$MailAttributesList = @()
        foreach ($attribute in $CorrectAttributes.Keys) {
            if ($currentAttributes.$attribute -ne $correctAttributes.$attribute) {
                $params = @{Identity = $username; $attribute = $correctAttributes.$attribute }
                $mailUpdatedAttribute = $CorrectAttributes.$attribute | Out-String
                Set-ADUser @params

                [void]$MailAttributesList.add("$attribute")

            }
            else {
                Write-Host "$username '$attribute' is correct"
            }
            $MailAttributesList
            $MailAttributesList = @()
        }
    }

Upvotes: 0

Views: 170

Answers (1)

Theo
Theo

Reputation: 61148

Taken from the part where you test if the user exists and then check which attributes need to be updated, I'd do this:

# personally, I hate using -Properties *
# better to list the properties you are trying to update:
$userAttribs = 'SamAccountName','Name','DisplayName','UserPrincipalName',
               'GivenName','Surname','Path','City','Country','Department',
               'EmployeeId','MobilePhone','Manager','Office','PostalCode',
               'POBox','ScriptPath','Street','Title'

# test if a user with that name already exists
$user = Get-ADUser -Filter "SamAccountName -eq '$username'" -Properties $userAttribs -ErrorAction SilentlyContinue
if ($user) {
    # always https://learn.microsoft.com/en-us/powershell/module/addsadministration/set-aduser
    # for the correct parameter names!
    $CorrectAttributes = @{
        SamAccountName    = $username
        Name              = "$firstname $surname"
        DisplayName       = "$firstname $surname"
        UserPrincipalName = "[email protected]"
        GivenName         = $firstname
        Surname           = $surname
        Path              = "CN=Users,DC=domain,DC=com" #change to switch based of Users Branch
        City              = $_.City
        Country           = $_.Country #NOTE: This Feild must be the 2 digit Country Code, NOT the String Name of athe Country.
        Department        = $_.OrgDepartmentName
        EmployeeId        = $_.EmployeeId
        MobilePhone       = $_.Mobile
        Manager           = $_.Manager  # must be a DistinguishedName, GUID, SID or SamAccountName
        Office            = $_.Branch
        PostalCode        = $_.PostalCode
        POBox             = $_.PostOfficeBox
        ScriptPath        = $_.scriptPath
        Street            = $_.StreetName
        Title             = $_.Title
    }

    # create a new empty hashtable to store the properties that need updating
    $UpdateAttribs = @{}
    # capture all changes on behalf of the email body
    $changes = foreach ($prop in $CorrectAttributes.Keys) {
        if ($user.$prop -ne $CorrectAttributes[$prop]) {
            # output an object with the property to be changed for the email
            [PsCustomObject]@{
                Property = $prop
                OldValue = $user.$prop
                NewValue = $CorrectAttributes[$prop]
            }
            # add the value to update in the the $UpdateAttribs hashtable
            $UpdateAttribs[$prop] = $CorrectAttributes[$prop]
        }
    }

    if ($changes) {  # or do: if ($UpdateAttribs.Count)
        # perform the changes
        $user | Set-ADUser @UpdateAttribs
        # send the email to the admin
        $mailParams = @{
            To         = '[email protected]' 
            From       = '[email protected]'
            Subject    = 'User attributes changed'
            Body       = "Changed AD attributes for user $username`r`n" + ($changes | Format-Table -AutoSize | Out-String)
            SmtpServer = 'smtp.yourcompany.com'
            UseSsl     = $true
            Credential = $MailCred
            # maybe more parameters go here..
        }
        Send-MailMessage @mailParams
    }
    else {
        Write-Host "All attributes for user '$username' are correct"
    }
}
else {
    Write-Warning "User $username does not exist"
}

P.S. The code could be shortened if you have your input CSV file use the correct headers, so they match the property names for Set-ADUser exactly..

Upvotes: 1

Related Questions