【问题标题】:PowerShell The Try statement is missing its Catch or Finally blockPowerShell Try 语句缺少其 Catch 或 finally 块
【发布时间】:2018-11-20 06:27:19
【问题描述】:

我是非常 PowerShell 新手,最近才发现这个工具的瑰宝。我拼凑了几个不同的脚本,以允许我在驱动器中搜索 Excel 文件并查看它们是否包含字符模式。我想我有我需要的所有东西,但是我一直收到大括号错误(据我所知)。

我的脚本的正则表达式部分有意义吗?下面的两行是否足以确定每个单元格值是否与规定的模式匹配?

$formula = $workSheet.cells.item($row,$column).value
if($formula -match [regex]$REGEX)

另外,我在尝试运行脚本时不断收到错误消息(有关详细信息,请参阅代码后)。我已经尝试添加和删除大括号,因为这是消息不断告诉我的问题。

我的脚本是这样写的:

Function Search-Files-For-Patterns {
    [cmdletbinding()]
    Param (
        [parameter(Mandatory)]
        [ValidateScript({
            Try {
                If (Test-Path -Path $_) {$True}
                Else {Throw "$($_) is not a valid path!"}
            }
            Catch {
                Throw $_
            }
        })]
        [String]$Source,       
        [parameter(Mandatory)]
        [string]$SearchText
    )
    $LogCSV = "X:\PowerShell\Scrape.csv"
    $Filelist =  Get-ChildItem $Source -Filter '*.xls*' -Recurse
    $Excel = New-Object -ComObject Excel.Application
    $DisableAutomationSecurity = [Microsoft.Office.Core.MsoAutomationSecurity]::msoAutomationSecurityForceDisable
    $EnableAutomationSecurity = [Microsoft.Office.Core.MsoAutomationSecurity]::msoAutomationSecurityByUI
    $REGEX = "\d\d\d-\d\d\d-\d\d\d"

    $Excel.Application.AutomationSecurity = $DisableAutomationSecurity
    Remove-Item $LogCSV -ErrorAction SilentlyContinue

    Out-File -FilePath $LogCSV -InputObject "File;Count;NAS"
    #"File;Count" > $LogCSV                    
    foreach ($File in $Filelist) {
        $password = ""
        try {
            $Workbook = $Excel.Workbooks.Open($File.FullName, 0, 0, 5, $password)
            $Numbers = New-Object System.Collections.ArrayList
            $NumberCount = 0
            ForEach ($Worksheet in @($Workbook.Sheets)) {
                $rowMax = ($Worksheet.usedRange.rows).count
                $columnMax = ($Worksheet.usedRange.columns).count
                For($row = 1 ; $row -le $rowMax ; $row ++) {
                    For($column = 1 ; $column -le $columnMax ; $column ++) {
                        $formula = $workSheet.cells.item($row,$column).value
                        #[string]$formula = $workSheet.cells.item($row,$column).value
                        if($formula -match [regex]$REGEX) {
                            $Numbers.Add("$($formula.Text);")
                            $NumberCount++
                            if ($NumberCount -eq 25) {break}
                        } #end for if $formula 
                    } #end for $column
                } #end for $row            
                if ($NumberCount -ge 10) {
                    Out-File -FilePath $LogCSV -InputObject "$($File.FullName);$NumberCount;$Numbers" -Append
                } #end if $numbercount >= 10
                $workbook.close($false)
            } #end foreach worksheet
            catch {
                Out-File -FilePath $LogCSV -InputObject "$($File.FullName);File is password protected - skipped;" -Append
            } #end catch
        } #end try <--ERROR OCCURS HERE
    } #end for each file

    $Excel.Application.AutomationSecurity = $EnableAutomationSecurity
    [void][System.Runtime.InteropServices.Marshal]::ReleaseComObject([System.__ComObject]$excel)
    [gc]::Collect()
    [gc]::WaitForPendingFinalizers()
    Remove-Variable excel -ErrorAction SilentlyContinue
} #end function
Search-Files-For-Patterns "X:\SomeFolder" "\d\d\d-\d\d\d-\d\d"

我在尝试运行时收到的错误消息是:

At X:\PowerShell\ScrapeG\Search-Files-For-Patterns.ps1:58 char:10
+         } #end try
+          ~
The Try statement is missing its Catch or Finally block.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : MissingCatchOrFinally

任何方向/帮助将不胜感激。

提前致谢。

【问题讨论】:

  • 您没有关闭 try 块。在} #end foreach worksheet 之后添加}
  • try {do-stuff} catch {error-handling} finally {finishing-moves}
  • 所以你在 try 块中有 catch 块。在尝试块之后,您需要在外面捕获块。更容易看出您是否使用 Visual Studio Code,真的很有帮助:) 另外 - Github 上有很棒的 importexcel 模块 - 不确定它是否支持导入受密码保护的文件,但可能值得一试。
  • @viRg } 的位置仅在您不小心将其写在#end foreach worksheet 之后的同一行中并且新的} 被解释为注释时才重要
  • @viRg 所以你有两个选择:1)github.com/dfinke/ImportExcel 2)你可以直接从 powershell Gallery 下载,像这样 Install-Module -Name ImportExcel

标签: regex excel powershell


【解决方案1】:

尝试使用catch [System.Exception]

如果出现错误:

Catch 块缺少它的语句块

这是一个编译时错误。 如果你有这样的事情:

try 
    {
        ...
    }
    catch (System.Exception)
    {
        write $_ 
        return 'test'
    }

尝试将异常括在括号中,而不是括号:

try 
    {
        ...
    }
    catch [System.Exception]
    {
        write $_ 
        return 'test'
    }

【讨论】:

  • 在catch 和异常之间留一个空格很重要。在这种情况下,[System.Exception]。这样的错误导致了一个非常具有误导性的错误,我花了一段时间才弄清楚我做错了什么
【解决方案2】:

您的catch 声明放错了位置。目前它放在foreach 块之后,但它必须放在try 块之后。

        } #end foreach worksheet
    } #end try, SHOULD END TRY BEFORE STARTING CATCH
    catch {
        Out-File -FilePath $LogCSV -InputObject "$($File.FullName);File is password protected - skipped;" -Append
    } #end catch
} #end for each file

【讨论】:

    猜你喜欢
    • 2021-07-10
    • 2018-10-14
    • 2010-11-25
    • 2013-05-20
    • 2018-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多