Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Path to the XLSX file
- $filePath = "C:\path\to\your\xlsx\file.xlsx"
- # Create an instance of Excel COM object
- $excel = New-Object -ComObject Excel.Application
- # Open the workbook
- $workbook = $excel.Workbooks.Open($filePath)
- # Select the first worksheet
- $worksheet = $workbook.Worksheets.Item(1)
- # Get the range of data in the worksheet
- $range = $worksheet.UsedRange
- # Get the number of rows in the range
- $rowCount = $range.Rows.Count
- # Prompt the user for the search word
- $searchWord = Read-Host -Prompt "Enter the search word"
- # Create an array to store the results
- $results = @()
- # Iterate through each row in the range (excluding the header row)
- for ($i = 2; $i -le $rowCount; $i++) {
- # Get the file path from the desired column (adjust the column index accordingly)
- $filePath = $range.Item($i, 1).Text
- # Check if the file exists
- if (Test-Path $filePath) {
- # Read the file content
- $fileContent = Get-Content -Path $filePath -Raw
- # Check if the search word is part of the file content
- if ($fileContent -like "*$searchWord*") {
- # Get the file name and the part of the path next to the search word
- $fileName = Split-Path -Leaf $filePath
- $splitPath = $fileContent -split [regex]::Escape($searchWord)
- $nextPart = $splitPath[-1]
- # Create a custom object with the file name and the next part of the path
- $result = [PSCustomObject]@{
- FileName = $fileName
- NextPart = $nextPart.TrimStart("\")
- }
- # Add the result to the array
- $results += $result
- }
- }
- }
- # Close the workbook and quit Excel
- $workbook.Close()
- $excel.Quit()
- # Release the COM objects
- [System.Runtime.Interopservices.Marshal]::ReleaseComObject($range) | Out-Null
- [System.Runtime.Interopservices.Marshal]::ReleaseComObject($worksheet) | Out-Null
- [System.Runtime.Interopservices.Marshal]::ReleaseComObject($workbook) | Out-Null
- [System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel) | Out-Null
- [System.GC]::Collect()
- [System.GC]::WaitForPendingFinalizers()
- # Export the results to a text file
- $results | Export-Csv -Path "C:\path\to\output\results.txt" -Delimiter "`t" -NoTypeInformation
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement