B
@rc4 said:@BaconBits said:It may work, but it's logically incorrect and will easily fail.
It works for almost everyone in our system, with the exception of the one or two people who have duplicate names.
So what you're saying is that it's wrong.
Try this:
$LdapServer = 'fqdn.of.ldap.server.org';
$rootDSE = [adsi]'LDAP://RootDSE';
$AD = [adsi]('LDAP://{0}/{1}' -f $LdapServer, $rootDSE.DefaultNamingContext.ToString());
$ADSearcher = [adsisearcher]$AD;
$ADSearcher.PageSize = 5;
$ADSearcher.CacheResults = $false;
$ADSearcher.PropertiesToLoad.AddRange('mail');
$ADSearcher.Filter = '(&(samaccountname={0})(objectCategory=person)(objectClass=user))' -f $env:USERNAME;
$email = $ADSearcher.FindAll() | ForEach-Object { $_.Properties.Item('mail'); };
$ADSearcher.Dispose();
if ($email -eq $null) { Write-Error "Man, we ain't found shit.";}
else {
$email | ForEach-Object { Send-MailMessage -To $_ -From $_ -Bcc 'root@server.org' -Subject "Why you logging in to my servers?" -Body "Boy, you done fucked up now." -SmtpServer your.mail.server.org; }
}
Yes, it's a lot more code, but it's actually doing what you want instead of using the wrong attributes and pounding that square peg into the round hole. If you don't want to use MathNerdCNU's method that's a hell of a lot more elegant, this is going to be the most accurate way to do what you're trying to.
The variable $LdapServer should have the FQDN of the domain controller you prefer people connect to to run queries against. You can leave that portion of the LDAP string out if you don't care.
You definitely want to be sure to call $ADSearcher.Dispose(). That class is horrible about memory leaks. If you don't ever enumerate the results, it actually sticks around in memory. I've accidentally left PowerShell sessions open like that overnight, and come in to a system that was locked up because of it.