Developmentish

August 1, 2011

Quick Tip: Email from your scripts

Filed under: Powershell, Quick Tips — Martyn Gough @ 10:50 pm

One of the most useful things I’ve found is using PowerShell to send an email… Doesn’t sound like much, but it provides power-users a nice “don’t worry, it’s done” email and everyone sleeps that little bit more soundly with some confirmation.

So lets hit the script then…

            
$msg = new-object System.Net.Mail.MailMessage            
$msg.From = new-object System.Net.Mail.MailAddress("Martyn@Developmentish.com")            
$msg.To.Add("Somebody@Someplace.com")                
$msg.Subject = "New Email"            
$msg.Body = "Look at this <b>TEXT</b>"            
            
$htmlView = [System.Net.Mail.AlternateView]::CreateAlternateViewFromString($msg.Body, "text/html")            
$msg.AlternateViews.Add($htmlView)            
            
$smtpClient = new-object System.Net.Mail.SmtpClient            
$smtpClient.Host = "MyEmailServer"            
$smtpClient.Port = 25            
$smtpClient.Send($msg)            

The more seasoned developer will point out that this script is using elements that are more common in .Net applications.
Why? Because PowerShell can!

Lets break it down…

Firstly we create a System.Net.Mail.MailMessage and bind it to the $msg variable.
Then we add a From, a To, a Subject and a body (notice the inclusion of HTML tags in the message).

We could just leave the $msg object as is, but the problem we have is that the body is in plain text… And our body contains HTML.
Here we create an “alternate view” from the message body converting text to HTML.
Then we add the alternate view to our $msg object.

Now comes the geeky part. We need to point our message code at an SMTP server… We create an SMTP client object… to this we declare the host (server) and the port (25 is default). Once we have this all set up, we use the SMTP Client to send our message object.

Once you’ve got the hang of it you can use it for things like error reporting when combined with the ole try catch method. Quick example below tries to get the contents of a folder, if it can’t it sends an email:

            
Try {            
    Get-ChildItem "C:\SomePlace"            
}            
Catch {            
    $msg = new-object System.Net.Mail.MailMessage            
    $msg.From = new-object System.Net.Mail.MailAddress("Martyn@Developmentish.com")            
    $msg.To.Add("Somebody@Someplace.com")                
    $msg.Subject = "New Email"            
    $msg.Body = "Look at this TEXT"            
            
    $htmlView = [System.Net.Mail.AlternateView]::CreateAlternateViewFromString($msg.Body, "text/html")            
    $msg.AlternateViews.Add($htmlView)            
            
    $smtpClient = new-object System.Net.Mail.SmtpClient            
    $smtpClient.Host = "MyEmailServer"            
    $smtpClient.Port = 25            
    $smtpClient.Send($msg)            
}            

Enjoy!

July 6, 2011

Quick Tip: Finding text in files

Filed under: Powershell, Quick Tips — Martyn Gough @ 12:43 pm

Lets start with this:

            
Get-ChildItem "C:\Test" | Select-String "password" | Select-Object Filename, LineNumber,Path, pattern, Line            

This will find all files in the C:\Test directory, search them using the Select-String cmdlet for a match on the work “password”, then return the filename, line number, path, the word it matched (in this case password) and the actual line of text containing the word.

That’s a lot for one line huh? How does that work?
Well it’s all thanks to the pipe character |. This enables us to pass one object into the next segment of code… I like to think of the pipe meaning “and then”. Using that logic the code says: Find a file and then look for text and then return results. Makes sense like that.

So what happens if we want to delete all files with certain words in them on your whole drive? Maybe you have top secret government information you need to dispose of, or maybe you’re paranoid. Either way we use the pipe:

            
Get-ChildItem "C:\" -recurse | Select-String "Reverse Microwave" |  ForEach-Object { Remove-Item $_.Path  -force }            

In this scenario I’ve backed up all my plans for a reverse microwave (one that freezes stuff really really quickly) to a flash drive and thus need to delete any trace of it from my computer before the people who make ice cube trays track me down.

It’s pretty simple to see what I’ve done, I did a ForEach-Object loop meaning each result is then passed into the code contained in the {curly brackets}. Here I’ve just done a remove-item using -force (to cater for read only violations).

That’s all from me!

May 5, 2011

Quick Tip: Creating folders based on dynamic dates

Filed under: Powershell, Quick Tips — Martyn Gough @ 1:39 pm

Lets get things started with a favourite of mine… Powershell. An immensely powerful tool which makes automation of mundane tasks a breeze. (anyone wanting to learn should check out the TechNet webinars here!)

Anyway… onto the point of today’s post, Dates and times.

The cmdlet for pulling the current date and time is Get-Date:

Get-Date

This will return:

    05 May 2011 13:06:29

Ok, handy, but what if we need this formatting in a different way say for a folder name or similar? well we use the -format parameter.

Get-Date -format "dd-MM-yyyy"

This will return:

    05-05-2011

So lets work on that folder name theory, say we want to create a folder with yesterday’s date.

$dYesterday  = (Get-Date) - (New-TimeSpan -days 1)            
$dYesterday  = Get-Date $dYesterday -format "dd-MM-yyyy"            
            
$sFolderName = "C:\$dYesterday"            
            
New-Item -type Directory -path $sFolderName            

Lets go through this step by step then…

This uses Get-Date to pull the current date time then subtracts a time span of 1 day from the value:

$dYesterday  = (Get-Date) - (New-TimeSpan -days 1)

We use Get-Date to pull the previously calculated value so that we can apply the -format parameter on it… We don’t do this in the above calcuation as some formats can convert the datetime value into a string causing the subtraction of the timespan to fail:

$dYesterday  = Get-Date $dYesterday -format "dd-MM-yyyy"

We create a path for our new folder as C:\yesterday’s date in dd-MM-yyyy format:

$sFolderName = "C:\$dYesterday"

Finally we use New-Item to create a directory using our dynamically created path variable from above:

New-Item -type Directory -path $sFolderName            

If you wish to delve deeper into dates and timespans in powershell, just remember you already have all you need at your fingertips:

Get-Help Get-Date
Get-Help New-Timespan

Wew, there we go, my first ever technical blog… I know this assumes some working knowledge of powershell, but hey it’s a tip not a step by step.

Enjoy!

Blog at WordPress.com.

Design a site like this with WordPress.com
Get started