2017-10-08 47 views
0
$servers = Get-Content "servers.txt" 
$collection = $() 
foreach ($server in $servers) 
{ 

    $status = @{ "ServerName" = $server; "TimeStamp" = (Get-Date -f G) } 
    if (Test-Connection $server -Count 1 -ea 0 -Quiet) 
    { 
     $status["Results"] = "Online" 
     $test = Test-Connection -ComputerName $server -Count 4 -ErrorAction SilentlyContinue 
     $stat = $test | Measure-Object -Property ResponseTime -Average -Maximum -Minimum 
     $status["Avg"] = $stat.Average 
     $status["Lost"] = [string]$(100*(4-$test.Count)/4) + ' %' 

    } 
    else 
    { 
     $status["Results"] = "Down" 
    } 
    New-Object -TypeName PSObject -Property $status -OutVariable serverStatus 
    $collection += $serverStatus 
} 
$collection | Out-GridView | Export-Csv -LiteralPath .\ServerStatus3.csv -NoTypeInformation 

如何輸出爲表格?但這樣的列是在一個特定的序列
如果我刪除「失去」列,它顯示爲一個表。 See 但是,正如您所看到的,第一列未完全顯示。
我需要的最重要的事情是每個集成都能立即顯示在屏幕上!格式化集合的輸出

+0

'$ collection | Select-Object -Property <以所需順序在此處插入字段> | Out-GridView | [...]' –

回答

0

如果您正在尋找只是格式化,您可以使用Format-Table-Wrap參數。

但是,如果使用格式表,則會丟失對象結構,結果將只是文本,不能導出爲CSV文件。

$ collection | Out-GridView | Export-Csv -LiteralPath。\ ServerStatus3.csv -NoTypeInformation

上述代碼行將生成一個空的csv文件。你必須把-Passthru參數設置爲Out-GrifView,我建議不要使用Out-GridView,因爲它會打破這裏的自動化。

0
  1. 可以建立一個對象直接
  2. 你應該存儲值沒有統一爲平均或丟失(統一爲打印,存儲始終沒有統一 - >如果一天你想使用沒有必要這個值來重新拆分此字符串)
  3. 不nessary通過數組來傳遞,輸出寫你的對象,並使用管道使用

試試這個:

Get-Content "c:\temp\servers.txt" | %{ 

    if (Test-Connection $_ -Count 1 -ea 0 -Quiet) 
    { 
     $test = Test-Connection -ComputerName $_ -Count 4 -ErrorAction SilentlyContinue 

     [pscustomobject]@{ 
     ServerName=$_ 
     Results="Online" 
     TimeStamp=Get-Date 
     Avg=($test | Measure-Object -Property ResponseTime -Average).Average 
     PercentLost=100*(4-$test.Count)/4 
     } 
    } 
    else 
    { 
     [pscustomobject]@{ 
     ServerName=$_ 
     Results="Down" 
     TimeStamp=Get-Date 
     Avg=$null 
     PercentLost=$null 
     } 
    } 

} | export-csv "c:\temp\resultstats.csv" -notype 
+0

感謝您的幫助,但是如何讓它將每行連續輸出到控制檯?如果我把'export-csv''ft -AutoSize'放在最後,然後打印表格,但我想立即看到執行結果。 –

+0

$ result = get_content .......在最後,將$ result打印到屏幕上 – Esperento57