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
STOP 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.