Alexander Meise
Alexander Meise

Reputation: 1438

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 
}

Upvotes: 0

Views: 1790

Answers (2)

Alexander Meise
Alexander Meise

Reputation: 1438

Set Execution-Policy  RemoteSigned
$servidores = Get-Content "C:\ServerList.txt"
Write-Output ("----------------Running script-----"+(Get-Date).ToString()+"--  -----------")
Write-Output "--------------------------Servers in scope----------------------------"
Write-Output $servidores
foreach ($server in $servidores){
Write-Output ("---Executing Search on Server:---"+$server+"----at:"+(Get-    Date).ToString()+"-------------")
$result= Invoke-Command -ComputerName $server -ScriptBlock {Select-String -    Pattern "password" -Path C:\*.txt -AllMatches}
if ($result -ne $null){
Write-Output $result.ToString() 
}
}Read-Host -Prompt "Press Enter to exit"

Upvotes: 0

BenH
BenH

Reputation: 10044

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

Upvotes: 2

Related Questions