【问题标题】:Grabbing the most recent log file from multiple computers (powershell)从多台计算机获取最新的日志文件(powershell)
【发布时间】:2017-06-14 19:50:12
【问题描述】:

我想创建一个脚本,该脚本将访问 .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

【问题讨论】:

    标签: powershell


    【解决方案1】:
    • 擦除输出文件;但你可以直接覆盖它。
    • 将所有内容放入变量中;但您只能使用一次。
    • 用双输出处理和编码怪异组成你自己的管道分隔 CSV,PS 有很好的 CSV 处理。
    • 无需测试文件是否存在,因为你不知道它会被调用什么。

    例如

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-19
      • 1970-01-01
      • 1970-01-01
      • 2020-09-09
      • 1970-01-01
      • 2013-11-26
      • 2015-03-28
      • 2021-01-24
      相关资源
      最近更新 更多