我有一个像这样的日志文件包含很多行。
connected to TEST01:5555
connected to Android-TEST:5555
up time: 01:39:18, idle time: 06:20:37, sleep time: 00:00:00
connected to TEST02:5555
up time: 01:39:27, idle time: 05:53:12, sleep time: 00:00:00
connected to TEST03:5555
up time: 01:38:27, idle time: 06:24:59, sleep time: 00:00:00
connected to TEST04:5555
up time: 01:39:21, idle time: 06:25:28, sleep time: 00:00:00
connected to TEST05:5555
up time: 18 days, 22:03:19, idle time: 74 days, 04:25:45, sleep time: 00:00:00
connected to TEST06:5555
connected to TEST07:5555
connected to TEST08:5555
up time: 01:49:30, idle time: 07:11:23, sleep time: 00:00:00
connected to TEST09:5555
up time: 18:53:29, idle time: 3 days, 01:51:07, sleep time: 00:00:00
我想通过powershell输出一个报告,其中只包含2列,设备名称和运行时间。
我找不到一种方法来制作一个模式来做select-string或where-object。
请问好吗?
答案 0 :(得分:3)
这适用于您的数据吗?
$filename = '<filename>'
$regex =
@'
(?ms)connected to (\S+)\s*
up time: ([0-9:]+).+
'@
Get-Content $filename -Delimiter 'sleep time' |
foreach {
if ($_ -match $regex)
{
[PSCustomObject]@{
DeviceName=$Matches[1]
UpTime = $Matches[2]
}
}
}
答案 1 :(得分:2)
$LogFile = Get-Content test.txt
$TempHashTable = @{}
$TheList = @()
For ($i=0;$i -lt $LogFile.Length;$i++) {
#We will check each line since we don't know when
#we will get an actual connection, we have to check
#the line after the current line, if it contains
#the phrase "up time: " then we know we've got a
#good connection
$j=$i+1
If (![string]::IsNullOrEmpty($LogFile[$j])) {
#Here we just check to make sure the string isn't
#a completely blank or "Null" value.
If ($LogFile[$j].Contains("up time: ")) {
#So we know this line is good, add it to $TheList
$ComputerName = $LogFile[$i] -Replace "connected to "
$ComputerName = $ComputerName -Replace ":5555"
#This is the next line containing the uptime
$ArrUptime = $LogFile[$j] -split ", idle time: "
$Uptime = $ArrUptime[0] -Replace "up time: "
#Add to the hashtable
$TempHashTable.ComputerName = $ComputerName
$TempHashTable.Uptime = $Uptime
#Create the object and add it to $TheList of
#computers array
$TheList += New-Object PSObject -property $TempHashTable
}
}
}
$TheList
输出:
ComputerName Uptime
------------ ------
Android-TEST 01:39:18
TEST02 01:39:27
TEST03 01:38:27
TEST04 01:39:21
TEST05 18 days, 22:03:19
TEST08 01:49:30
TEST09 18:53:29
答案 2 :(得分:2)
另一个允许任何其他数据存在于您的文件中的正则表达式示例。需要PowerShell 3.0+才能使用[pscustomobject][ordered]
以及-Raw
的{{1}}开关
Get-Content
您的样本输出
Get-content "c:\temp\log.txt" -raw | Select-String -pattern '(?smi)connected to\s+(\w+):.*?up time:\s+(.*?), idle time:' -allmatches | %{$_.Matches} | %{
[pscustomobject][ordered]@{
Workstation = $_.Groups[1].Value
Uptime = $_.Groups[2].Value
}
}
从评论中更新
即使您更新了文件,我也只需进行一些小改动即可将输出计入&#34;天&#34;一部分。否则它仍在工作。如果你仍然好奇,我猜你也许没有PowerShell 3.0?无论哪种方式,这确实有效。只有问题可以从组中获取您想要的主机名。现在我的代码拉了第一个。