How to automatically call Pop-Location at end of scope

Viewed 1264

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

Function MyFunction($Location)
{
  Push-Location $Location
  # do other stuff here
  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:

Function MyFunction($Location)
{
  Setup-BothPushAndPopHere $Location
  # do other stuff here
  # at the end of the scope, Pop-Location is automatically called
}
3 Answers

Here is a cool way to do it with script blocks

function withPath($action,$path) {
    Push-Location $path
    try 
    {
        & $action
    }
    finally
    {
        Pop-Location
    }
}
withPath { 
    Get-Location | Write-Host 
    withPath {
        Get-Location | Write-Host 
        throw "oh no, an inner exception!"
    } 'Program Files' #relative path
} 'C:\' 
Related