捕获后继续

问题描述 投票:0回答:1

我有以下代码块。我想在 catch 块中运行函数后继续。我知道这是不可能的,我只是想知道是否有一种方法可以点源或其他一些技巧来使其工作。

代码:

Function Get-LatestEdgeWebDriver {

  $modpath = (join-path -path ($env:PSModulePath -split ';')[0] -ChildPath 'Selenium\3.0.1\assemblies')
  $filepath = Join-Path -Path $modpath -ChildPath 'edgedriver_win64.zip'
  Set-Location $modpath

  $EdgeExe = Get-ItemPropertyValue 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\msedge.exe' "(default)"
  $version = (Get-Item $EdgeExe).VersionInfo.ProductVersion
  $download = 'https://msedgedriver.azureedge.net/' + $version + '/edgedriver_win64.zip'
  $web_request = Invoke-WebRequest -Uri $download
  if(($web_request.Content[0] -is [byte]) -and $web_request.StatusCode -eq 200){
    if ($PSversiontable.psversion.major -eq 7) {
      Set-Content -Path $filepath -asBytestream -Value $web_request.Content -ErrorAction SilentlyContinue -Force
    } else {Set-Content -Path $filepath -Encoding Byte -Value $web_request.Content -ErrorAction SilentlyContinue -Force}
  }

  Load-Module '7Zip4Powershell'
  Expand-7Zip -ArchiveFileName .\edgedriver_win64.zip -TargetPath . 
  Start-Sleep -seconds 5
  if((Get-Process | Where-Object {$_.Name -eq 'MicrosoftWebDriver'} | Measure-object).Count -gt 0)
  {Get-Process -name MicrosoftWebDriver | kill -Force}
  Move-Item -Path .\msedgedriver.exe -Destination .\MicrosoftWebDriver.exe -Force
  Remove-Item -Path .\edgedriver_win64.zip -Force -ErrorAction SilentlyContinue
  Set-Location $scriptpath
  write-host -ForegroundColor yellow "Edge Webdriver Updated to $version version.."
}


# Code starts here

# More code here

try {
      $Driver = Start-SeEdge -StartURL $uri -PrivateBrowsing -Quiet -Minimized -WarningVariable $warn -WarningAction SilentlyContinue
      Enter-SeUrl $uri -Driver $Driver -WarningAction SilentlyContinue
    }catch {[System.Management.Automation.MethodInvocationException]{
        write-host -ForegroundColor Yellow "Old version of Edgedriver found. updating... "
        Get-LatestEdgeWebDriver
        # Continue out of catch
        }
    }

# continue code below this line
powershell try-catch
1个回答
0
投票

使用

finally{}
应该可以解决您的问题,但如果代码未到达捕获点,它也会运行。所以你的工作流程将变成

  1. 尝试 -> 最后(如果没有错误)
  2. 尝试 -> 捕获(如果错误) -> 最后

如果您希望它仅在 catch 运行后运行,您可以保留一个标志并在 catch 块中更新它并签入finally 块。代码可以如下所示:-

let flag = 0;
try {
// your code here
} catch {
flag = 1;
// your code here
} finally {
if(flag) {
// your code here
}
}
© www.soinside.com 2019 - 2024. All rights reserved.