Wednesday, August 05, 2009

PowerShell and .NET Framework – Similarities and Differences!

When I teach PowerShell, I point out the consistency within and across the product. When you learn something, it can be broadly used in other circumstances. This is the power of knowledge transfer – learning things once and using that knowleldge to solve other problems.

Of course, despite the consistency that’s there, there is a level of in-consistency to manage. There are things that are just not particularly intuitive – and you just have to learn those differences. There is definitely a learning curve when it comes to learning PowerShell! I’ve published what I learn as I go along – I posted an article about .NET and Powershell last December where I looked at how you access .NET from PowerShell.

With a bit of learning, via posts like mine or from Newsgroup.Forum posts, most PowerShell users can look at a bit of documentation on .NET or  WMI, and work out how to access the relevant class,  method, etc. But every so often, stuff that looks obvious isn’t! This fact (feature???) bit me over the weekend when I was working on the Get-System.Environment script that I published over on my PowerShell Scripts blog.

I was playing around with the System.Environment class, and in particular the Environment.SpecialFolder enum. Just looking at it, I felt if I can use one enum like this,

PSH [C:\foo]: [system.Enum]::GetValues([system.dayofweek])
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday

Then I should be able to to do something like this (which as you see I can’t):

PSH [C:\foo]: [system.Enum]::GetValues([System.Environment.SpecialFolder])
Unable to find type [system.Environment.SpecialFolder]: make sure that the assembly containing this type is loaded.
At line:1 char:60
+ [system.Enum]::GetValues([system.Environment.SpecialFolder] <<<< )
    + CategoryInfo          : InvalidOperation: (system.Environment.SpecialFolder:String) [], RuntimeException
    + FullyQualifiedErrorId : TypeNotFound

Then, after some searching, I discovered may mistake!  Instead of [System.Environment.SpecialFolder], I needed to specify [System.Environment+SpecialFolder]. As shown here:

PSH [C:\foo]: [system.Enum]::GetValues([system.Environment+SpecialFolder])
Desktop
Programs
Personal
Personal
Favorites
Startup
Recent
SendTo
StartMenu
MyMusic
DesktopDirectory
MyComputer
Templates
ApplicationData
LocalApplicationData
InternetCache
Cookies
History
CommonApplicationData
System
ProgramFiles
MyPictures
CommonProgramFiles

Sure – that was obvious, NOT! But another hurdle on my learning curve!

No comments: