Search code examples
excelpowershellexport-to-excel

Searching contents of text files on remote computers and exporting to excel file using powershell and export-excel


I'm trying to search the contents of text files on remote computers from computers.txt which includes

Pc1
Pc2
Pc3
Pc4

And export it using export-excel PowerShell module using this code:

$directory = $PSScriptRoot
$computers = Get-Content -Path $directory\computers.txt
$searchwords = 'word1','word2','word3'

Foreach ($computer in $computers) {
    $path = "\\$computer\C$\test\logs"

    Foreach ($sw in $searchwords) {
        $excel = Get-Childitem -path $path -recurse -Include "*.txt" |
        Select-string -pattern "$sw" |
        Select-object pattern, linenumber, line, path |
        Export-excel $file -autosize -startrow 1 -tablename pattern -worksheetname "errors" -passthru
        
        $ws = $excel.workbook.worksheets['errors']
        $excel.save()
    }
}

The problem is that it will only export the contents of pc4 which is the last in the computers.txt list.

Thanks in advance


Solution

  • Adding the -append switch on export-excel will get this working.

    It was added as part of the release on 10/30/2017 - https://github.com/dfinke/ImportExcel#whats-new-in-release-52