How to automatically call Pop-Location at end of scope

Question:

Let’s say I have a simple scope that is book-ended with Push-Location and Pop-Location:

Is there any way to set it up at the beginning of the scope so that I don’t have to remember to put the Pop-Location at the end? Something like this:

Answer:

Short answer: No.

My take on Push-Location and Pop-Location is that you should generally avoid them, and adapt your script to use the path names in commands instead; in other words, instead of:

Just do:

(simplified example)

If you must use the pattern, consider try/finally:

As this helps with unexpected exceptions or the user interrupting program execution.

I typically use the try/finally pattern when the code is outside my control; most often when loading the SQLPS module since it changes the current location to the SQL server provider which in my experience causes everything that uses the current location to become much slower.

As Eris points out, it’s also useful when dealing with native applications. This can be especially true if it’s painful to escape quotes around path names with spaces, or the application wouldn’t handle it correctly anyway.

Source:

How to automatically call Pop-Location at end of scope by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply