2015-04-24 185 views
0

我正在創建一個腳本來獲取從文本文件讀入的一組PC的正常運行時間/最後一次重新啓動。格式化輸出文件

我可以輸出結果到文件,但它不斷重複我不想要的列標題。基本上我想輸出頭的第一行,然後每行輸出數據下面的數據。下面的代碼重複了輸出文件的列標題,並且行之間有很多空格。輸出到CSV會更容易處理?

這是我的代碼。第一個Out-File命令是覆蓋文件,如果它存在,基本上清理文件。

$computers = Get-Content "c:\temp\ps\pc.txt" 

out-file -FilePath "C:\temp\ps\output.txt" 
foreach ($computer in $computers) 
{ 
    $Computerobj = "" | select ComputerName, Uptime, LastReboot 
    $wmi = Get-WmiObject -ComputerName $computer -Query "SELECT LastBootUpTime  FROM Win32_OperatingSystem" 
    $now = Get-Date 
    $boottime = $wmi.ConvertToDateTime($wmi.LastBootUpTime) 
    $uptime = $now - $boottime 
    $d =$uptime.days 
    $h =$uptime.hours 
    $m =$uptime.Minutes 
    $s = $uptime.Seconds 
    $Computerobj.ComputerName = $computer 
    $Computerobj.Uptime = "$d Days $h Hours $m Min $s Sec" 
    $Computerobj.LastReboot = $boottime 
    $Computerobj 
    out-file -FilePath "C:\temp\ps\output.txt" -in $computerobj -append 
} 

回答

0

試試這個:

$computers = Get-Content "c:\temp\ps\pc.txt" 

#Create a report variable as an array to hold all our data 
$report = @(); 

#No longer necessary 
#out-file -FilePath "C:\temp\ps\output.txt" 

foreach ($computer in $computers) 
{ 
    $Computerobj = "" | select ComputerName, Uptime, LastReboot 
    $wmi = Get-WmiObject -ComputerName $computer -Query "SELECT LastBootUpTime  FROM Win32_OperatingSystem" 
    $now = Get-Date 
    $boottime = $wmi.ConvertToDateTime($wmi.LastBootUpTime) 
    $uptime = $now - $boottime 
    $d =$uptime.days 
    $h =$uptime.hours 
    $m =$uptime.Minutes 
    $s = $uptime.Seconds 
    $Computerobj.ComputerName = $computer 
    $Computerobj.Uptime = "$d Days $h Hours $m Min $s Sec" 
    $Computerobj.LastReboot = $boottime 

    #Add the computer to the report array 
    $report += $Computerobj 
} 

#Uncomment this if you need to see the report as well as write it to a file 
#Write-Output $report 

out-file -FilePath "C:\temp\ps\output.txt" -in $report 

現在你可以操縱報告作爲一個整體,所以你甚至可以像$report = $report | Sort-Object -Property ComputerName末尾添加的東西排序計算機名稱的報告,或將其過濾Where-Object

+0

這也很好。愛你的燻肉片! – user3364233

3

ForEach-ObjectExport-Csv的管線鋪設將是一個更好的辦法:

$now = Get-Date 

Get-Content -Path 'C:\temp\ps\pc.txt' | ForEach-Object { 
    $wmi = Get-WmiObject -ComputerName $_ -Class Win32_OperatingSystem 
    $boottime = $wmi.ConvertToDateTime($wmi.LastBootUpTime) 
    $uptime = $now - $boottime 
    New-Object -Type PSObject -Property @{ 
    'ComputerName' = $_ 
    'Uptime'  = '{0} Days {1} Hours {2} Min {3} Sec' -f $uptime.Days, 
        $uptime.Hours, $uptime.Minutes, $uptime.Seconds 
    'LastReboot' = $boottime 
    } 
} | Export-Csv -Path 'C:\temp\ps\output.txt' -NoType 

如果同時需要在文件中並在控制檯上的數據,你可以使用ConvertTo-CsvTee-Object

Get-Content 'c:\temp\ps\pc.txt' | ForEach-Object { 
    ... 
} | ConvertTo-Csv -NoType | Tee-Object -FilePath 'C:\temp\ps\output.txt' 
+0

Ansgar非常感謝。輸出在csv中是完美的 – user3364233