Get-content管道选择字符串并检索ComputerName

问题描述:

我想写一个脚本,我可以查看远程服务器的列表,搜索某些文件类型。然后,如果文件包含一个特定的字符串,我想知道哪个文件在哪个计算机上。Get-content管道选择字符串并检索ComputerName

我从基础开始,但是当我做选择字符串时,我无法检索文件,也找不到计算机名称,它只是输出与我在脚本中相同的字符串。

我敢肯定我失去了一些基本的东西,但任何建议在这里将不胜感激。

$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 } 

我希望能够选择文件名,Pscomputername和选择字符串。

我发现打破管道更容易。我已成功测试此代码:

$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 
} 
+1

谢谢,我真的很感激。我对电源管理相当陌生,只是通过尝试完成我需要完成的任务来学习。我昨天晚上开始做类似的事情,但却一直停留在输入流中返回的文件名。 – JonnyBoy