gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 09:45:05 25 4
gpt4 key购买 nike

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

Function MyFunction($Location)
{
Push-Location $Location
# do other stuff here
Pop-Location
}

有什么方法可以在范围的开头设置它,这样我就不必记住将 Pop-Location 放在末尾?像这样的东西:
Function MyFunction($Location)
{
Setup-BothPushAndPopHere $Location
# do other stuff here
# at the end of the scope, Pop-Location is automatically called
}

最佳答案

简短的回答:没有。

我对 Push-Location 的看法和 Pop-Location是您通常应该避免它们,并调整您的脚本以在命令中使用路径名;换句话说,而不是:

Push-Location $Location
Get-ChildItem
Pop-Location

做就是了:
Get-ChildItem $Location

(简化示例)

如果必须使用该模式,请考虑 try/ finally :
Push-Location $Location
try {
# ...
} finally {
Pop-Location
}

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

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

Eris指出,它在处理 native 应用程序时也很有用。如果使用空格转义路径名周围的引号很痛苦,或者应用程序无论如何都无法正确处理它,则尤其如此。

关于powershell - 如何在范围结束时自动调用 Pop-Location,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35923637/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com