Sometimes, you need to tattle on a user to their manager. But how to find out who their manager is, and their email address? Here is how I did it with PowerShell.
At my job, stale user accounts are not tolerated. Inactive accounts are disabled after a period of time, with no warning. However, I wanted to at least notify the persons manager that the account was disabled, and why.
First thing you should know, this PowerShell script requires the Active Directory Module to be loaded (Import-Module ActiveDirectory).
The whole thing can be encapsulated in a one-liner, as shown below. Simply replace $UserNameHere with the name of the user. I like to use the SamAccountName for this.
$Manager=(Get-AdUser (Get-aduser $UserNameHere -properties manager).manager -properties emailaddress).EmailAddress
The downside of the one-liner is that there is no error checking. If there is no manager defined, then there is no email address to be found, resulting in a big, ugly, red error message.
To get around that fail, we can plug it into a cmdlet:
[CmdletBinding()]
Param(
[Parameter(Mandatory=$True,Position=1)]
[string]$UserName
)
$ManagerName=(Get-ADUser $UserName -Properties Manager).manager
if($ManagerName){
$ManagerEmailAddress=(Get-Aduser $ManagerName -properties EmailAddress).EmailAddress
} else {
$ManagerEmailAddress=$Null
}
$ManagerEmailAddress
Here, we are using a parameter called $UserName. The rest of the script is broken out to first get the managers name. If the manager field is blank, nothing is returned. If the manager field contains a value, then the script retrieves the email address, and prints it out on screen.
By piping the output of this code to the Send-MailMessage cmdlet, you can send a message to the users manager, letting him know of action taken against his employees account.