如何在范围结束时自动调用Pop-Location

Por*_*Man 3 powershell

假设我有一个简单的范围,通过Push-Location和Pop-Location以书结尾:

Function MyFunction($Location)
{
  Push-Location $Location
  # do other stuff here
  Pop-Location
}
Run Code Online (Sandbox Code Playgroud)

有没有办法在范围的开头设置它,这样我就不必记得将Pop-Location放在最后?像这样的东西:

Function MyFunction($Location)
{
  Setup-BothPushAndPopHere $Location
  # do other stuff here
  # at the end of the scope, Pop-Location is automatically called
}
Run Code Online (Sandbox Code Playgroud)

bri*_*ist 6

简答:不.

我在起飞Push-LocationPop-Location是,你应该尽量避免使用它们,适应你的脚本使用,而不是命令的路径名; 换句话说,而不是:

Push-Location $Location
Get-ChildItem
Pop-Location
Run Code Online (Sandbox Code Playgroud)

做就是了:

Get-ChildItem $Location
Run Code Online (Sandbox Code Playgroud)

(简化示例)

如果必须使用该模式,请考虑try/ finally:

Push-Location $Location
try {
    # ...
} finally {
    Pop-Location
}
Run Code Online (Sandbox Code Playgroud)

因为这有助于意外异常或用户中断程序执行.

当代码不在我的控制范围内时,我通常使用try/ finallypattern; 最经常在加载SQLPS模块时,因为它将当前位置更改为SQL服务器提供程序,根据我的经验,使用当前位置的所有内容变得慢得多.

正如Eris指出的那样,它在处理本机应用程序时也很有用.如果使用空格转义路径名称周围的引号很痛苦,或者应用程序无法正确处理它,那么尤其如此.

  • @briantist仅当所有命令都是powershell本机的时候.我很确定git不使用`$ PSDefaultParameterValues` (2认同)