假设我有一个简单的范围,以 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
and Pop-Location
是您通常应该避免它们,并调整您的脚本以在命令中使用路径名;换句话说,而不是:
Push-Location $Location
Get-ChildItem
Pop-Location
Just do:
Get-ChildItem $Location
(简化示例)
如果必须使用该模式,请考虑try
/finally
:
Push-Location $Location
try {
# ...
} finally {
Pop-Location
}
因为这有助于解决意外异常或用户中断程序执行。
我通常使用try
/finally
当代码超出我的控制范围时的模式;最常在加载时SQLPS
模块,因为它将当前位置更改为 SQL Server 提供程序,根据我的经验,这会导致使用当前位置的所有内容变得更慢。
As Eris https://stackoverflow.com/users/2100227/eris指出,它在处理本机应用程序时也很有用。如果用空格转义路径名周围的引号很痛苦,或者应用程序无论如何都无法正确处理它,则尤其如此。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)