A Random, but useful Powershell script

I use powershell more and more these days. Granted, I am still but a novice with it, I occasionally will come up with something I think is cool. And recently, I did just that.

The scenario:

I will often get requests to give a list of people access to a directory. Seems simple enough. The problem here is that the list of people will usually be a haphazardly thrown together list with no particular formatting. For example, it could be all together with no spaces (Name,email(fullname)) or a list with lots of extra info thrown in (Name, email, likes, dislikes, turn-ons, etc)

What I need in our case, is simply the first part of their email address, since our email suffix does not match up with the domain. 

So I made a script that extracts all email addresses from any text file using a regular expression, and then lops off the email suffix... Anything from the @ symbol on, and then pops open a notepad file with the usernames nicely listed (for use in another script even!) It runs in the blink of an eye, and I find it extremely useful and just plain cool. 

Of course you could modify something like this to do similar tasks based on the info you need to extract, but for my uses, this is great. 

#Extract Email Addressess from text file, and then remove @ suffix.
#Thrown together by Joel Spangler 2015.

#Paste source text to input file
#This extracts any email address and lists it in emails.txt
$input_file = ‘c:\scratch.txt’
$output_file = ‘c:\emails.txt’
$regex = ‘\b[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}\b’
select-string -Path $input_file -Pattern $regex -AllMatches | % { $_.Matches } | % { $_.Value } > $output_file

#Set email list as a variable
$emails = gc C:\emails.txt

#Now we remove the @suffix
$output = foreach ($i in $emails) {$i.Substring(0, $i.IndexOf('@'))} 
$output | Out-File C:\EmailResult.txt

#Opens up resulting list of usernames in notepad
Notepad C:\EmailResult.txt