For being a Microsoft employee, I am almost ashamed to admit that I am a novice at PowerShell. Also taking into account my scripting history with both Sybase and DB2 on UNIX systems, PowerShell should be a very comfortable place for me. That being said, in the SQL Server space I do not always get many occasions to use PowerShell. Well, today was a great opportunity. I needed to pull out each instance of a particular error from a SQL errorlog file. Initially I was going to use LogParser, which is a great little tool for such a job, but I also wanted to give PowerShell a shot. Unless I make myself use it, I will never truly learn it.
I initially thought about what I would have done in the UNIX world…. well that’s easy…. grep. I did a quick Bing search and the Select-String PowerShell command popped right up along with a great example. Thanks TechNet! A quick test on the command line and I got a great screen full of text. Well, now I needed to pipe that to a file. All I had to do there was Bing ”Powershell pipe output to file” and there is was…Out-File. They couldn’t name it much easier than that! Without even looking at theTechNet page I ran the script that I came up with and was a little disappointed. It worked, but the output file was formatted with the same width as the PowerShell command window, yuck. Therefore, I had to actually go look at the TechNet article on Out-File and there it showed the –width parameter. A little tweak and then I was done. The command goes as follows (note that I added the line break in there for formatting):
Get-Content SQL_Errorlog.TXT | Select-String " of I/O requests taking longer than
15 seconds to complete" | out-file IOErrors.txt -width 500
Yes, this is a very rudimentary task. Yes, this script is extremely simple. BUT, It was more of an exercise to help me get out of my comfort zone a little and learn something new.
Let’s face it folks, PowerShell is something that all SQL DBAs will eventually need to know, especially for automation purposes. This is the way that the OS and many other Microsoft products are going as well (just ask any SharePoint engineer). Take some time and learn it! There are great resources out there such as TechNet, The Scripting Guy, and countless other blogs to help you learn.