Prof. Powershell

Value Proposition

If any colleagues aren't convinced of the PowerShell power, this week's trick might convert 'em.

I trust that many of you realize how much value Windows PowerShell brings to the party. A large part of this value is in the form of increased efficiency. In effect, you can accomplish a great deal with little effort. While I understand and appreciate that there is still a PowerShell learning curve, it is not as steep as something like VBScript. And once you have some basic PowerShell literacy you'll be amazed at what you can do.

This time, I want to offer a practical example that you might want to share with your colleagues who still aren't convinced by the PowerShell story. Here is a relatively simple VBScript that creates a CSV report of files in the %TEMP% directory (although it could be any folder):


On Error Resume Next
Set objShell=CreateObject("WScript.Shell")
strDir=objShell.Environment("Process").Item("TEMP")
strFile=objShell.SpecialFolders("MyDocuments") & "\FileReport.csv"
Set objfso=CreateObject("Scripting.FileSystemObject")
Set objFile=objfso.CreateTextFile(strFile,vbTrue)
objFile.WriteLine "File,Size,Created,LastModified"

Call EnumFolder(strDir)

objFile.Close()

Sub EnumFolder(strFolder)
On Error Resume Next
  Set objFolder=objfso.GetFolder(strFolder)

  For Each strFile In objFolder.Files
    objFile.WriteLine strFile.path &"," & strFile.size & "," &_
    strFile.DateCreated & "," & strFile.DateLastModified
  Next

  For Each objSub In objFolder.SubFolders
    Call EnumFolder(objSub.Path)
  Next
End Sub

This script uses the FileSystemObject to query the specified folder and create the CSV file. The script is about 25 lines and must be saved to a text file and executed. Here is a one-line PowerShell command that does the same thing:

dir $env:temp -recurse -force -ea SilentlyContinue |
where {$_ -is [system.IO.FileInfo]} |
select-object Fullname,Length,CreationTime,LastWriteTime |
Export-Csv -Path "$env:userprofile\documents\FileReport2.csv" -NoTypeInformation

I've broken some of the expressions to make it easier to follow. There's very little in this command that a PowerShell beginner couldn't come up with. You'll get practically the same results. The only difference is that the CSV header will be different because property names are different. But that too, can be remedied with only a little more work:

dir $env:temp -recurse -force -ea SilentlyContinue |
where {$_ -is [system.IO.FileInfo]} |
select @{Name="File";Expression={$_.Fullname}},`
@{Name="Size";Expression={$_.Length}},@{Name="Created";Expression={$_.CreationTime}},`
@{Name="LastModified";Expression={$_.LastWriteTime}} |
Export-Csv -Path "$env:userprofile\documents\FileReport2.csv" -NoTypeInformation

If you need a report like this frequently, you can save this one-line command into a .ps1 script file and run it. Even better: Let's say you need reports like this for a number of folders on a regular basis. Take advantage of PowerShell's modular nature and achieve even more efficiency. There are many ways you could handle this; here's one possible script:

Param([string]$path=$env:temp,
  [string]$logpath="$env:userprofile\documents"
      )

#change any \ in the path to _
$folder=$path.Replace("\","_")
#remove any :
$folder=$folder.Replace(":",$null)
#define a report path
$ReportPath=Join-Path $logPath "$folder.csv"
write-host "Logging results to $ReportPath" -ForegroundColor Green
dir $path -recurse -force -ea SilentlyContinue |
where {$_ -is [system.IO.FileInfo]} |
select @{Name="File";Expression={$_.Fullname}},`
@{Name="Size";Expression={$_.Length}},`
@{Name="Created";Expression={$_.CreationTime}},`
@{Name="LastModified";Expression={$_.LastWriteTime}} |
Export-Csv -Path $reportPath -NoTypeInformation

Now all you need is a text file of directory paths. Use Windows PowerShell to go through the list and pass each one to your script:

Get-content folders.txt | foreach {c:\scripts\FolderReport.ps1 -path $_}

Consider how much VBScript it would take to achieve the same result. With PowerShell, you get something that's flexible and interactive.

Here's my challenge to you: The next time you have an administrative automation need, see how long it takes you to accomplish it using VBScript and then compare it to how long it takes using Windows PowerShell. At the end, which is easier to maintain in the long run and offers the most flexibility and value to your organization?

Don't forget: If you need some PowerShell help to drop by the forums at ScriptingAnswers.com.


About the Author

Jeffery Hicks is a Microsoft MVP and an IT veteran with almost 20 years of experience, much of it spent as an IT consultant specializing in Windows server technologies. He works today as an independent author, trainer and consultant. His latest book is Managing Active Directory with Windows PowerShell 2.0: TFM (SAPIEN Press 2011). Follow Jeff on Twitter and on his blog.

Reader Comments:

Wed, Aug 4, 2010

It's appalling the lengths people will go to just to avoid having to learn something new. Nobody's asking anybody to quit using VBScript when it's the right tool for the job. PowerShell is an ADDITIONAL tool. Yes, Jeff's example plays to PowerShell's strengths - because, for the job he's illustrating, PowerShell is a better tool than VBScript. He's trying to make a point: Neither VBS nor PSH are universally perfect for all things. Yes, PowerShell's syntax is different. Yes, it requires different usage patterns. Suck it up. You learned VBScript (which frankly is NOT all that intuitive, especially for the tens of thousands of admins with NO programming background). You've learned many other syntaxes - this is one you can learn too. Stop whining. Nobody is purporting that PowerShell is universally "better" than anything else. It IS better and more efficient at many things, though - learn to recognize those things and use the right tool. VBS is easier because you KNOW it. PowerShell will be just as easy if you take the time to learn it. If you don't, fine... see where you wind up in a few years. Heck, there are still people programming in Visual FoxPro, so the IT industry will clearly tolerate a wide range of tools. If you're disappointed in things like array variable support in PowerShell - it's BECAUSE YOU HAVEN'T TAKEN THE TIME TO LEARN POWERSHELL PROPERLY. It isn't a scripting language. If you're enumerating things and sticking them into arrays, you're trying to impose a scripting-style usage pattern onto something that isn't a scripting language. Learn to use PowerShell properly on jobs for which it is well-suited. For a bunch of alleged professionals who work in an industry that literally thrives on change, it's truly annoying to see how many people simply resist that change. You don't want to learn PowerShell, ever? Fine. You think it's the work of the devil? Fine. Shut up and let those people who ARE interested in it learn. Everyone else learning PowerShell should be no threat to you. Frankly, if you dislike PowerShell so much I'm not even sure why you bother to read this column, except that you just want to be contrary. Geez.

Tue, Aug 3, 2010 Michael @Michael_Simmons

Huge PowerShell fan here. It opened doors for me, and while I knew about VBS I barely scratched the surface. PowerShell was mind-blowing and awesome right from the start. Extremely frustrating for me in the beginning, but a challenge I embraced. I have done soem large projects now that I couldn't have done before PowerShell. Looking back, I could have done them in VBS, or Perl. But for me it's PS. Now, can you administer SharePoint 2010 with VBS or Perl as easily as PowerShell? or Exchange? Active Directory? As far as "show me the basics", try 'get-help about_for' 'get-help about_foreach' 'get-help about_if' to get some of the basics - or just simply 'help about' to help with a lot of the concepts. The comments on this article are better than the article itself. lol. Thanks Jeff

Tue, Aug 3, 2010 Grant

The thing is, learning PowerShell isn't really optional if you're an admin. Microsoft is going to be putting more and more functionality into it and more and more of Microsoft server tools are going to be using it, it's completely inescapable. The way it was put to me by Don Jones is that MS is creating a two tier system for admins. Tier 1 admins will be able to use the GUI and Tier 2 admins will be using PowerShell. We already have that divide in SQL Server where advanced admins use TSQL and beginners are stuck with Management Studio. It's worth it to me to be in that Tier 2 group. I'll be able to do more, faster, than the guys in Tier 1, which means I'm more likely to be employed over the long term.

Tue, Aug 3, 2010 Jeff Hicks

The big difference is that VBS is a scripting language and PowerShell is a command shell, that just happens to let you script. Yes, you have to learn some syntax and shell language basics, but I think they are still easier to learn than VBScript. My one line PowerShell example is without a doubt arcane if you've never seen PowerShell before and it could have been written differently. In a script I might have. But I wanted to show that from the command line you can type a command that is the same as a 25 line VBScript. If you want flexibility, then create a PowerShell function. I appreciate all the comments.

Wed, Jul 28, 2010 Rich

As a admin I used to do everything in Perl then switched to vbscript when it became the better alternative. Now PowerShell is out. I too had difficulty making the switch from Vbscript to PS. But I stuck with it and took a class. After taking the class I was all powershell no vbscript any longer. You can run vbscript from PS. I too believe what gives the vbscripters a hard time following PS is that the examples of PS always use the hard to follow alias commands and always show just the one liners. Once you get the basic concepts down of PS you will not go back to vb.

Wed, Jul 28, 2010 g

PS can't be just dismissed because as with any tool it provides more power and usability in some situations than the other options. I'm just not sure that this is a good example of one of those situations.

Admin scripts working with AD and its objects are where I like to use PS. That's why we all know more than one language. Right tool for the right job, right? That's why EVERYBODY knows JS; it's unavoidable.
If someone isn't already familiar with VBS and Perl then this may be a good way to go. (I'm assuming that someone that spells it as "Pearl" is not that familiar with the Perl language.)

Wed, Jul 28, 2010 Craig

I’m a System Administrator and a self-taught PowerShell person. I learned PS from reading articles, blogs, etc. on the internet and by reading “Windows PowerShell 2.0: Administrator’s Pocket Consultant” by William R. Stanek. It took me a little time and effort to lean some things however I feel comfortable with PS and I really love it. If you need a quick query of something it is very handy. If you need a script to automate a process it’s good for that as well. You can use it to administer AD, Exchange, SQL and more (yes, you need the latest versions of these products). Sure you can use VBS or Pearl or whatever to do some of the same things however; I can do these things quickly and easily in PowerShell. I highly recommend Quest PS Commands for AD as they provide more power and ease of use for AD related administration. http://www.quest.com/powershell/activeroles-server.aspx

Wed, Jul 28, 2010 g

I started working with PowerShell because of all the hype, but after 2 months I've pretty much backed off. It's cool, but it's devolved into a "why bother?" sort of thing.
And while VBS handles what I need and is easy to understand, the truth is that writing this in one line of Perl is more than likely how I would go. I'd just add a comment or two for clarity. (I always comment my code anyway.)
Perl is still my power language of choice. Reducing 25 lines of code down to 1, now that's cool!

Wed, Jul 28, 2010 Greg Wisconsin

Wow is this a stretch! The example provided is so completely designed to Powershell's strengths -- and even then, simply customizing the headers for example 2 shows that the Powershell almost doubles in size and is, frankly, far LESS readable than the VBScript. I could do the entire thing in one line of Perl, for that matter... not that anybody could read it. What if you want to filter your output to show folders/files where the date is more than 7 days old? Or better yet for this example, show only files and folders last modified BEFORE the system was last rebooted as any temp file created since the system was last rebooted might still be in use. Or maybe you want to report on only folders above a certain size. Most of these options would require only 1-3 lines of additional VBScript -- and many, many more than that of Powershell code. On the merits, Powershell is yet another enhanced batch file language that in certain circumstances provides some cool options. VBScript is a true scripting language, that does some things more easily and some things less easily than Powershell. Both have advantages and disadvantages. Bottom line, it's another option -- but it doesn't eliminate the need for VBScript.

Wed, Jul 28, 2010 Steve Cleveland, Ohio

Ditto that. In particular I've been quite disappointed by the handling of array variables under Powershell and it has nearly driven me to drink everytime I've had to code under it.

Wed, Jul 28, 2010

#1, I'm assuming from the large amount of articles purporting PowerShell to be "better" than VBS that I am not the only Admin that is having a hard time making the switch. #2, If you have to convince the world that you are better; you just might not be. #3, for anyone that has ever programed in any language, the VBS is a LOT easier to understand. When I look at the powershell script and compare it to the VBS, I just can't follow the PS script. Show me some of the basics of programming: For-Next, If-Then, etc... then we can talk about PS being a language...

Add Your Comment Now:

Your Name:(optional)
Your Email:(optional)
Your Location:(optional)
Comment:
Please type the letters/numbers you see above