PowerShell Try语句缺少Catch或Finally块

时间:2018-06-11 04:01:07

标签: regex excel powershell

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

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

$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

非常感谢任何方向/帮助。

提前致谢。

2 个答案:

答案 0 :(得分:1)

您的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

答案 1 :(得分:0)

尝试使用捕获[System.Exception]

如果出现错误:

  

Catch块缺少其语句块

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

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

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

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