Powershell 将日志文件格式化为表
我有以下代码Powershell 将日志文件格式化为表,powershell,administrator,Powershell,Administrator,我有以下代码 function ping-test($hosts) { $conn = [System.Collections.ArrayList]@($hosts) [int]$hostsamount = $conn.Count foreach($co in $conn) { $check = Test-Connection $co -Count 3 -ErrorAction SilentlyContinue $zugriffz
function ping-test($hosts) {
$conn = [System.Collections.ArrayList]@($hosts)
[int]$hostsamount = $conn.Count
foreach($co in $conn)
{
$check = Test-Connection $co -Count 3 -ErrorAction SilentlyContinue
$zugriffzeit = $check | select ResponseTime | Measure-Object ResponseTime -Average
$avg = [system.math]::Round($zugriffzeit.Average)
$zeit = Get-Date -Format HH:mm:ss
if($check -eq $null)
{
$pcre = Write-Output $co
$pire = Write-Output 'False'
$zure = $null
}
else
{
$pcre = Write-Output $co
$pire = Write-Output 'True'
$zure = Write-Output "$avg ms"
$zure = $zure.Replace(' ','')
}
[void]$re.Add([PSCustomObject] @{PCName=$pcre; PingResult=$pire; Zugriffszeit=$zure; Zeit=$zeit} )
**$log = "Host:{0} Ping: {1} Zugriffszeit: {2} Zeit: {3}" -f $pcre, $pire, $zure, $zeit
$log >> $logpath**
[int]$recount = $re.Count
[int]$eff = $recount - $hostsamount
try {
$re.RemoveRange(0, $eff)
}
catch{
Write-Host $Error
}
}
return $re
}
我使用以下代码(在该函数中)
问题是:我想和Colums的“Host”、“Ping”、“Zugriffszeit”和“Zeit”组成一张表。
如何形成此表并在某处另存为.txt或.log文件
Thx用于帮助使用与输出相同的数据 要导出到csv(如果以后要以编程方式重新使用数据),请执行以下操作: 如果您想再次将其格式化到一个漂亮的表格中,请使用以下简单方法:
Import-Csv $logpath |Format-Table
如果您只是想在日志文件中精确地列出输出:
$re |Format-Table |Out-String |Out-File $logfile
@Jessen展示了csv的导入和导出 但是,如果您必须使用.txt或.log文件(正如您的问题所述),那么请使用PSCustomObject和Out文件
[PSCustomObject]@{
Host = $pcre
Ping = $pire
Zugriffszeit = $zure
Zeit = $zeit
} | Out-File $logpath
稍后导入它,如:
Get-Content $logpath
没用。在下面出现此错误:“System.Collections.Hashtable”类型的值“System.Collections.Hashtable”无法转换为“System.Management.Automation.PSCustomObject”类型。可能是因为你误解了我。我有相同的代码来创建一个表以将值保存在数组中。但是现在我想把表保存在一个日志文件中。也许你可以更进一步。我也要谢谢你的帮助,兄弟。我用导出和导入csv解决了这个问题。这不是最好的解决方案,但目前它仍然有效。在这种情况下,我应该首先导出CSV,然后导入它,格式化一个表并再次输出,这意味着将有两个文件输出。是否有可能只输出一个格式为表的文件。不,只需执行
$re |导出Csv…
,然后在最后一行执行返回$re
,它仍将显示在控制台中不仅在控制台中,而且我还希望有一个日志文件。导出csv后,文件很难读取。这就是为什么我想从导出文件中格式化一个表。问题是,如果我这样做,将会有两个文件(一个是csv文件,另一个是我想要的日志文件)。如何格式化此表并保存在一个表中file@keeran对不起,我误解了你的问题,请参阅更新的答案
[PSCustomObject]@{
Host = $pcre
Ping = $pire
Zugriffszeit = $zure
Zeit = $zeit
} | Out-File $logpath
Get-Content $logpath