Just a Tech Guy

Preventing A Disaster (with Powershell)

So, I walked into a production issue this morning at work that could have been easily prevented. A process we run at work moves files to a directory then imports the information from those files. This occurs every day and the files being moved into the import directory will not overwrite any files that are already in that directory. Long story short the files imported were the wrong ones since the ones that needed to be dropped off were moved to a staging area instead. Had I known there were files in there a 5 minute fix to prevent this would have saved me a half day’s recovery. I decided to prevent this from happening again by running a simple script.

The following script checks the directory on a server for any files with the csv extension. If it doesn’t find any, then all is well, life goes on. If files are found, it emails/pages me so I can move those files before the process runs.

1      $filecheck = Test-Path "\\servername\directory\*.csv"
2      If ($filecheck) {
3            $SmtpClient = new-object system.net.mail.smtpClient
4            $SmtpServer = "localhost"
5            $SmtpClient.host = "exchange.server.address"
7           $msg = New-Object Net.Mail.MailMessage
8           $msg.From = "Your Server"
9           $msg.To.Add("email@address.net")
10        $msg.Subject = "Your Directory not Empty!"
11         $msg.Body = "The directory for the blah is not empty! " + (Get-Date)
12         $SmtpClient.Send($msg)
14                                }

Ok, broken down line one sets a variable querying whether or not the path listed exists. This variable saves as a boolean.  Line two does a simple If/Else statement. In Powershell Else will be assumed. Boolean equivalent of True is If($variable) if we needed to check for false we would use If(!$variable). Lines 3-12 are the lines needed to email with SMTP.

Line 3 creates the email object.
Line 4 uses the localhost as the SMTP server.
Line 5 defines the ‘real’ server to relay the email off of. You will need to put your company’s exchange or email server’s address in here and make sure it allows relays.
Line 7 Creates the Message object.
Line 8 is Whatever you want your email From address to say. (Can be anything)
Line 9 is where you add an email address to send to. For each email address you would like to send to, just add a line identical to this one and change the email address.
Lines 10 and 11 are obvious. Change to whatever you like.
Line 12 sends the email.

Let me know if you have any questions or suggestions.

– Jason

Leave comment

Your email address will not be published. Required fields are marked with *.