Powershell - read list of machines from txt file and output

by Meic at 2012-09-12 04:42:18


I am writing a Powershell cmd to:

1) read list of machines stored in a txt file
2) export each machine’s ‘applciation’, ‘error’ from event viewer
3) save as <computername>.csv
4) read next machine name and so on…

This is the cmd I use to output the remote event viewer for 1 machine (this works):

Get-EventLog application -computername MACHINE1| where{$.entrytype -eq"Error"} | Format-Table -auto -wrap | out-file -filepath c:\eventvwr1.txt

I am having trouble getting it to work with multiple machines.

I have created a txt file c:\machines_List.txt which contains machine names.

This is what I have tried:

Get-Content c:\machines_List.txt | Foreach-Object {Get-EventLog application -computername ???| where{$
.entrytype -eq"Error"} | Format-Table -auto -wrap | out-file -filepath c:????.csv}

This doesn’t work. I’m not sure what to put after -computername and ???.csv. Not even sure it would work anyhow.

Also, in my txt file which contains the machine names, how should I list them? A machine name per line or seperated with comma etc?

Any advice would be very much appreciated.

by RichLec at 2012-09-12 05:13:09
Figured I would take a stab at this. Please see script below.
$PC = Get-Content c:\machines_List.txt
Foreach ($obj in $PC) {
Get-EventLog application -computername $obj | where{$.entrytype -eq"Error"} | Format-Table -auto -wrap | out-file -filepath c]

Give this a shot and let us know if you hit any snags.

by poshoholic at 2012-09-12 06:02:22
Just to add to what Rich provided, you should list your machine names one per line in machines_List.txt. That way Get-Content will read them as an array so that you can process them properly in your script.
by RichardSiddaway at 2012-09-12 11:12:09
Only thing I would add is around the use of format-table. It won’t give you reusable objects in your output file. If you want to reuse the entries try this

Get-Content -Path machines.txt |
foreach {
Get-EventLog -LogName Application -EntryType "Error" -ComputerName $($
) |
Export-Csv -NoTypeInformation -Path "$($_).csv"
by Meic at 2012-09-13 04:52:45
Thanks very much for taking time to reply (Rich, Kirk and Richard). Very much appreciated.

New to Powershell so trying to find the easiest way to get it to run on a system ( save as PS1, signing it etc). One of the machines I will be running it from has Powershell 1 and the other has ver 2.

Never realised it wasn’t as simple as dbl clicking a .ps1 file to run it. Will let you know how I get on.

by dpetche at 2012-10-10 17:30:51
Don Jones has a very satisfying rant regarding why it is a very good thing that you cannot double-click a .ps1 file to execute it.

Check-out his earlier guest appearances on the PowerScripting Podcast or his TrainSignal videos.