Question

How do I properly use $_ in out-file? Here's my code:

get-content computers.txt | 
  Where {$_ -AND (Test-Connection $_ -Quiet)} |
    foreach { Get-Hotfix -computername $_ } | 
      Select CSName,Description,HotFixID,InstalledBy,InstalledOn |
        convertto-csv | out-file "C:\$_.csv"

I'm trying to execute a get-hotfix for all the computers listed in the text file then I want them to be exported to CSV with the computer name as the filename.

Was it helpful?

Solution

You need one pipeline to process the computers.txt files, and a nested one inside the foreach to process the list of hotfixes for each computer:

get-content .\computers.txt |
  Where {$_ -AND (Test-Connection $_ -Quiet)} |
    foreach { 
      Get-Hotfix -computername $_ |
        Select CSName,Description,HotFixID,InstalledBy,InstalledOn |
          convertto-csv | out-file "C:\$_.csv" 
    }

Edit: Changed computers.txt to .\computers.txt, as this is required for local paths in powershell

OTHER TIPS

i can see with this: get-content .\computers.txt | Where {$_ -AND (Test-Connection $_ -Quiet)} | foreach{ Get-Hotfix -id KB4012212 -computername $_ | Select CSName,Description,HotFixID,InstalledBy,InstalledOn | convertto-csv | out-file "C:\$_.csv" } i can see only in which PC is the fix (KB4012212) installed. it's possible to see the following

  • CSNAME Fix(Inst/NotInst)

    PC1 FIxInstalled

    PC2 FixNotinstalled

    PC3 FixnotInstalled

.. .. etc

I monkeyed with this for a while and nothing I found on-line worked until I used this combo. 

I used the method is this thread but it was SO slow and I wanted to learn more about using jobs so this is what ended up working for me on Windows 7 PS Ver 4. All other options were either too slow or did not return data from the remote system.

$VMs = get-content C:\WinVms.txt #Generate your hostnames list however you deem best.
foreach ($vm in $vms)
{
Write-Host "Attempting to get hotfixes on:" $vm
invoke-command -computername $vm -ScriptBlock {start-job -scriptblock {(get-hotfix | sort installedon)[-1]} | wait-job | receive-job} -AsJob
}
start-sleep 60 # give it a minute to complete
get-job | ? { $_.state -eq "Completed"} | receive-job -keep | export-csv c:\temp\win-patch.csv

you can check your failures too like this: 

get-job | ? { $_.state -eq "Failed"} 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top