2

I want to create a script that will access computers on a .txt file and grab the latest log file from each and output the file and computer name into a new document. I've searched around feel confident that I can achieve this by combining the following two examples in some way, but I'm not entirely sure how. To get files from the same location on multiple computers:

$Computers = get-content "C:\Computers.txt"
$OutFile = "C:\Results.txt"

#Erase an existing output file so as not to duplicate data
out-file -filepath $OutFile

foreach ($Computer in $Computers)
{

if (test-path \\$computer\c$\temp\logfile.txt)  #test to make sure the file 
exists
{
#Get the CreationTime value from the file
$FileDate = (Get-ChildItem \\$computer\c$\temp\logfile.txt).CreationTime

#Write the computer name and File date separated by a unique character you 
can open in Excel easy with"
"$Computer | $FileDate" | out-file -FilePath $OutFile -Append -Encoding 
ascii
}
else
{
#File did not exist, write that to the log also
"$Computer | FILE NOT FOUND" | out-file -FilePath $OutFile -Append -Encoding 
ascii
}
}

To get the latest file in a directory

$dir = "C:\test_code"
$latest = Get-ChildItem -Path $dir | Sort-Object LastAccessTime -Descending 
| Select-Object -First 1
$latest.name

1 Answer 1

1
  • erase the output file; but you can just overwrite it.
  • put everything in variables; but you only use them once.
  • make up your own pipe delimited CSV with double output handling and encoding weirdness, PS has pretty good CSV handling.
  • no need to test if file exists, since you don't know what it will be called.

e.g.

Get-Content -Path "C:\Computers.txt" | ForEach-Object {    # Each computer

    # Get latest file
    $Latest = Get-ChildItem -Path "\\$_\c$\temp\*" | 
                  Sort-Object -Property LastAccessTime -Descending |
                  Select-Object -First 1

    # Make a custom object with the three things to go in the output CSV
    [PsCustomObject]@{
        Computer     = $_
        FileName     = if ($latest) { $Latest.Name }         else { "File not found" }
        CreationTime = if ($latest) { $Latest.CreationTime } else { "n/a" }
    }

} | Export-Csv c:\results.csv -NoTypeInformation -Encoding ASCII  # write the output csv
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.