Thursday, September 19, 2013

Use Processmonitor to debug command line syntax passed through PowerShell

If you are trying to find out why a certain formatted command within PowerShell is not working then I strongly recommend using ProcessMonitor tool from SysInternals suite of tools.  When you initially fire up the ProcessMonitor then it will show you lots of information and it can be overwhelming. 
So there is a powerful filtering functionality built into the utility.  Click on the filter tab and click on filter.
Then on the filter section add two filters as shown in the figure below.
The first filter is Path is “C:\Program Files\7-zip\7z.exe” and second one is Operation is “Load Image”.  After applying the filter and running my PowerShell script I can narrow down my desired line.
So if next time any command line utility is behaving weird then debug using ProcessMonitor.

Tuesday, September 17, 2013

Use PowerShell variables after escaping parsing in PowerShell v3.0

Recently I answered a question on StackOverflow related to passing parameters inside a PowerShell script to command line utility 7z.exe for unzipping zip files.  In the process of debugging the issue, I tried different options and learned few tricks in working with PowerShell and debugging issues. In this post, I am going to talk about how to pass powershell variables after you use the stop parsing --% trick.

Did you knew that you can tell PowerShell to stop parsing command?
In PowerShell V3, there is a neat trick you can use to tell it to stop parsing anything after typing --%. All you have to do is use --% after your command say & 7z.exe and PowerShell will directly pass the string after the --% to the command line utility. Check out below help snippet about parsing easily found by typing PS>C:\help about_parsing
    The stop-parsing symbol (--%), introduced in Windows PowerShell 3.0,
    directs Windows PowerShell to refrain from interpreting input as
    Windows PowerShell commands or expressions.
    When calling an executable program in Windows PowerShell, place the
    stop-parsing symbol before the program arguments. This technique is
    much easier than using escape characters to prevent misinterpretation.
So in the following example you don't have to include those parameters after --% in double or single quotes and do voodoo magic to figure out which one works.

But there is one problem with this approach, if you want to use PowerShell variables after the --% it won’t work. To solve this issue, you have to create a variable and initialize its value to --% and pass everything after it in variable(s). In the example below, I am using $stopparser variable with value --%. Finally I am passing everything using variables so PowerShell first evaluates the variables and then ignores parsing while executing the actual command. Isn't it magic.  I love PowerShell. If you know some neat trick about PowerShell then share in the comments section.