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

从多台计算机(powershell)获取最新的日志文件,powershell,Powershell,我想创建一个脚本,通过.txt文件访问计算机,从每个文件中获取最新的日志文件,并将文件和计算机名输出到新文档中。我已经四处搜索过了,我相信通过以某种方式结合以下两个示例可以实现这一点,但我不完全确定如何实现。 要从多台计算机上的同一位置获取文件,请执行以下操作: $Computers = get-content "C:\Computers.txt" $OutFile = "C:\Results.txt" #Erase an existing output file so as not to d

我想创建一个脚本,通过.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
  • 擦除输出文件;但是你可以直接覆盖它
  • 把一切都放在变量中;但你只能用一次
  • 用双输出处理和编码奇怪来构建自己的管道分隔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