从多台计算机中抓取最新的日志文件(powershell)

时间:2017-06-14 19:50:13

标签: powershell

我想创建一个脚本,该脚本将访问.txt文件中的计算机并从每个文件中获取最新的日志文件,并将文件和计算机名称输出到新文档中。我在周围搜索过,我有信心通过以某种方式结合以下两个例子来实现这一目标,但我并不完全确定如何。 要从多台计算机上的同一位置获取文件:

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

获取目录中的最新文件

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

1 个答案:

答案 0 :(得分:1)

  • 删除输出文件;但你可以覆盖它。
  • 将所有内容都放在变量中;但你只使用一次。
  • 使用双输出处理和编码怪异构成您自己的管道分隔CSV,PS具有非常好的CSV处理。
  • 无需测试文件是否存在,因为您不知道它将被调用。

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