Monday, February 24, 2014

Powershell Gotchas

In any language, you use long enough and you will end up in some dark corners where you don’t want to be. More you know these dark corners, more productive you will be. A good tool will have very few of these gotchas and all of them should be well documented and evangelized. We are all as good as our tools, knowing the strengths, weak points will help you picking the right tool for the job.

Powershell is powerful as the name implies, one of my coworker thinks, batch file set the bar very low, so Powershell seems refreshing and powerful to lot of people. I think that is very true. Batch file has lot of these gotchas. DOS commands can be very cryptic, Can’t set variable values without quote inside an if block, Commenting out a line with :: will behave weirdly in some places, use REM instead.

Though Powershell is refreshing, productive, intuitive, modern and powerful, it has its own set of quirks.
  1. Powershell functions return value differently than languages like C#, Java
  2. When passing arguments to functions, use space not comma. Commas convert the arguments into an array and pass  it as one argument.
  3. Functions has to be declared before they can be called. Problem with this approach is, you have to put your entry point/main logic at the end. If you have big script, you have to read it from bottom or the whole file. I always add a “main” function at the top, and do my logic inside that function and call this function as the last line.
  4. Unlike .bat file, you can’t run .ps1[extension for Powershell script files] by clicking/double clicking. Read Set-ExecutionPolicy. If you don’t want to change the system wide ExecutionPolicy, wrap it with a batch script.
  5. Unlike C style languages, ` is the escape character.
  6. $home and ~ are not same.

These are some useful articles on PowerShell gotchas

0 Comments :