抛出未捕获的异常时,如何恢复 PowerShell 脚本中的目录更改? [英] How do I revert a directory change in a PowerShell script when an uncaught exception is thrown?

查看:47
本文介绍了抛出未捕获的异常时,如何恢复 PowerShell 脚本中的目录更改?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 bash 中,如果我想更改单个命令的当前目录 do_thing,我会生成一个新的子 shell,在其中更改目录,运行

In bash, if I wanted to change the current directory for a single command do_thing, I'd spawn a new subshell in which to change the directory, running

(cd folderName; do_thing)

这个问题的正文建议在 PowerShell 中执行此操作的方法是使用 Push-Location 存储位置,并在命令完成运行后使用 Pop-Location.这有效,但并不理想:我必须记住在脚本的每个返回点写入 Pop-Location(例如,在每个异常之前,如果在推送位置时发生),以及未捕获的异常将保持当前目录不变.

The body of this question suggests the way to do it in PowerShell is to use Push-Location to store the location, and Pop-Location after the command has finished running. This works, but is not ideal: I have to remember write Pop-Location at every return point of the script (e.g. before each exception, if it occurs while a location is pushed), and an uncaught exception will leave the current directory as is.

有没有办法将当前目录重置为脚本开始时的目录,即使抛出未捕获的异常?

Is there a way to have the current directory reset to what it was at the start of the script, even if an uncaught exception is thrown?

推荐答案

try...catch...finally 是您正在寻找的构造!

try...catch...finally is the construct you're looking for!

这将允许您处理错误并执行最终操作;主 try 块是否成功.

This will allow you to handle your errors and perform a final action; whether the main try block was successful or not.

这是一个基本示例:

try {
    $x = 1/0
}
catch {
    Write-Warning "An error occurred"
}
finally {
    Write-Output "This always runs"
}

更适合您的情况:

Write-Output "BEFORE: $(Get-Location)"

try {
    Push-Location -Path "C:\temp\csv"
    Write-Output "DURING TRY: $(Get-Location)"
    $x = 1/0
}
catch {
    Write-Warning "An error occurred"
}
finally {
    Pop-Location
}

Write-Output "AFTER: $(Get-Location)"

结果:

之前:C:\temp

试用期间:C:\temp\csv

DURING TRY: C:\temp\csv

警告:发生错误

之后:C:\temp

这篇关于抛出未捕获的异常时,如何恢复 PowerShell 脚本中的目录更改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆