Search code examples
powershellpowershell-remoting

Get-content Pipe to Select String and retrieve ComputerName


I'm trying to write a script that I can look at a list of remote servers, search for certain file type. Then if the File consists with a certain string i want to know what file that is and on what computer.

I started with the basics but when I do Select-String I can't retrieve the file nor can i find the computer name, it just outputs the same string as i have in my script.

I'm sure i'm missing something basic but any suggestions here will greatly be appreciated.

$servers = ArrayofServers

    ForEach ($server in $Servers){ 
                invoke-command -computername $server {Get-ChildItem "D:\Folder\Location\Windows\" -Include *.txt -Recurse |

                Get-Content | 

                Select-String 'String to Select' | 

                Out-String 

    } -Credential $credential }

I want to be able to Select FileName,Pscomputername and Select-String.


Solution

  • I find it easier to break the pipeline. I have tested this code successfully:

    $Servers = @("ArrayofServers")
    foreach ($Server in $Servers)
    { 
        Invoke-Command -ComputerName $Server -ScriptBlock {
            $Results = $false
            $SearchResults = Get-ChildItem "D:\Folder\Location\Windows\" -Include *.txt -Recurse 
            foreach ($SearchResult in $SearchResults)
            {
                If ($SearchResult | Get-Content | Select-String 'String to Select')
                {
                    $SearchResult.FullName
                    $SearchResult | Get-Content
                    $Results = $true
                }
            }
            If ($Results)
            {
                $env:COMPUTERNAME
            }
        } -Credential $Credential 
    }