Today at work I had a need to query a bunch of databases for a particular, er, thing, and then send that thing, if found, to myself via email. I needed this to happen every morning. I decided, since we’re talking about a MS SQL and Windows 2003/2008 environment, that Powershell was the way to go. And it was – until I popped it into scheduler.
When executed as a scheduled task, the email didn’t send. Things before and after the email routine worked – the arrays populated, the log file filled – but the email didn’t go. Firing it from a Powershell manually, everything went fine.
Being the stubborn arse I am, rather than get to Googling I started ripping things apart. I had the query dump its results into a temp file that a separately scheduled script would open, parse, email and then clear. Same result: run manually everything worked peachy. Scheduled, no email.
In the end the problem was irritatingly simple. For some reason, when run as a scheduled task the script didn’t keep the socket open to the SMTP server long enough for a successful transmission. I added a Start-Sleep -s 5 right after the SMTP command to give it a 5 second breather before continuing on. Voila – email success. How silly.
I think I’m going to like Powershell just fine. Other than quirks like this, and getting used to the syntax, it’s easy enough – and it seems a lot of Windows specific stuff is streamlined, at least in comparison to my old go-to admin scripting languages.