Search code examples
powershellinvoke-commandselect-string

How to Remote Select-String several servers with Powershell


The idea is to search for a pattern on several servers with Select-String and Invoke-Command.

I am not able to get the $results back to the local server correctly and print it either in a file and/or also in the console (this is not so important).

What I need is to be able to see the results of the search (filename, line, match)

Set Execution-Policy  RemoteSigned
$servidores = Get-Content "C:\ServerList.txt"
(Get-Date).ToString()

Write-Output "----------------Running script------------------"
Write-Output "---------------Servers in scope :---------------"
Write-Output $servidores
Write-Output "-----------------Starting Loop-----------------"

$ToExecute = {
Select-String -SimpleMatch "password" -Path C:\*.* -Exclude C:\Users\Public\resultados.txt
}


 foreach ($server in $servidores){
$result = Invoke-Command -ComputerName $server -ScriptBlock $ToExecute 
Write-Output "----------Executing Search on Server:-----------"
(Get-Date).ToString();$server; 
Write-Output "------------------------------------------------"
Write-Output $result
Out-File $result C:\Users\Public\resultados.txt 
}

Solution

  • For Out-File if you are not piping, you will need to use the -inputobject flag. Because Out-File does not take the inputobject by position.

    Out-File -InputObject $result -path C:\Users\Public\resultados.txt 
    

    Otherwise you could use Tee-Object to replace the write-output/outfile.

    $result | Tee -filepath C:\Users\Public\resultados.txt