Finding content of Excel file in Powershell

前端 未结 1 1494
难免孤独
难免孤独 2020-12-21 09:30

I am currently working on a fairly large powershell script. However, I got stuck at one part. The issue is the following.

I have various reports with the same file n

相关标签:
1条回答
  • 2020-12-21 09:49

    If you want it to search the entire column for A to Z you would specify the range:

    $Range = $Worksheet.Range("A:Z")
    

    Then you should be able to execute a $Range.Find($SearchText) and if the text is found it will spit back the first cell it finds it in, otherwise it returns nothing. So start Excel like you did, then do a ForEach loop, and inside that open a workbook, search for your text, if it is found close it, move it, stop the loop. If it is not found close the workbook, and move to the next file. The following worked just fine for me:

    $Destination = 'C:\Temp\Backup'
    $SearchText = '3/23/2015  10:12:19 AM'
    $Excel = New-Object -ComObject Excel.Application
    
    $Files = Get-ChildItem "$env:USERPROFILE\Documents\*.xlsx" | Select -Expand FullName
    $counter = 1
    ForEach($File in $Files){
        Write-Progress -Activity "Checking: $file" -Status "File $counter of $($files.count)" -PercentComplete ($counter*100/$files.count)
        $Workbook = $Excel.Workbooks.Open($File)
        If($Workbook.Sheets.Item(1).Range("A:Z").Find($SearchText)){
            $Workbook.Close($false)
            Move-Item -Path $File -Destination $Destination
            "Moved $file to $destination"
            break
        }
        $workbook.close($false)
        $counter++
    }
    

    I even got ambitious enough to add a progress bar in there so you can see how many files it has to potentially look at, how many it's done, and what file it's looking at right then.

    Now this does all assume that you know exactly what the string is going to be (at least a partial) in that cell. If you're wrong, then it doesn't work. Checking for ambiguous things takes much longer, since you can't use Excel's matching function and have to have PowerShell check each cell in the range one at a time.

    0 讨论(0)
提交回复
热议问题