Advertisement
MedesJegve

Untitled

Jun 13th, 2023
26
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.28 KB | None | 0 0
  1. # Path to the XLSX file
  2. $filePath = "C:\path\to\your\xlsx\file.xlsx"
  3.  
  4. # Create an instance of Excel COM object
  5. $excel = New-Object -ComObject Excel.Application
  6.  
  7. # Open the workbook
  8. $workbook = $excel.Workbooks.Open($filePath)
  9.  
  10. # Select the first worksheet
  11. $worksheet = $workbook.Worksheets.Item(1)
  12.  
  13. # Get the range of data in the worksheet
  14. $range = $worksheet.UsedRange
  15.  
  16. # Get the number of rows in the range
  17. $rowCount = $range.Rows.Count
  18.  
  19. # Prompt the user for the search word
  20. $searchWord = Read-Host -Prompt "Enter the search word"
  21.  
  22. # Create an array to store the results
  23. $results = @()
  24.  
  25. # Iterate through each row in the range (excluding the header row)
  26. for ($i = 2; $i -le $rowCount; $i++) {
  27. # Get the file path from the desired column (adjust the column index accordingly)
  28. $filePath = $range.Item($i, 1).Text
  29.  
  30. # Check if the file exists
  31. if (Test-Path $filePath) {
  32. # Read the file content
  33. $fileContent = Get-Content -Path $filePath -Raw
  34.  
  35. # Check if the search word is part of the file content
  36. if ($fileContent -like "*$searchWord*") {
  37. # Get the file name and the part of the path next to the search word
  38. $fileName = Split-Path -Leaf $filePath
  39. $splitPath = $fileContent -split [regex]::Escape($searchWord)
  40. $nextPart = $splitPath[-1]
  41.  
  42. # Create a custom object with the file name and the next part of the path
  43. $result = [PSCustomObject]@{
  44. FileName = $fileName
  45. NextPart = $nextPart.TrimStart("\")
  46. }
  47.  
  48. # Add the result to the array
  49. $results += $result
  50. }
  51. }
  52. }
  53.  
  54. # Close the workbook and quit Excel
  55. $workbook.Close()
  56. $excel.Quit()
  57.  
  58. # Release the COM objects
  59. [System.Runtime.Interopservices.Marshal]::ReleaseComObject($range) | Out-Null
  60. [System.Runtime.Interopservices.Marshal]::ReleaseComObject($worksheet) | Out-Null
  61. [System.Runtime.Interopservices.Marshal]::ReleaseComObject($workbook) | Out-Null
  62. [System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel) | Out-Null
  63. [System.GC]::Collect()
  64. [System.GC]::WaitForPendingFinalizers()
  65.  
  66. # Export the results to a text file
  67. $results | Export-Csv -Path "C:\path\to\output\results.txt" -Delimiter "`t" -NoTypeInformation
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement