我正在尝试设置一个日志,该日志将从另一个日志文件中提取不同的信息,以便使用PowerShell记录由MDT构建的资产。我可以使用简单的get-content | select-string提取一行日志,以获得我需要的行,因此输出如下所示
[LOG[验证域凭据域\user]日志]!time="16:55:42.000+000“date=10-20-2017”component=“向导”context="“type="1”thread="“file=”向导
我很好奇是否有一种方法可以在单独的变量中捕获域\user、时间和日期之类的东西,以便以后可以在输出文件中以类似的方式在单行中传递另一个数据。
发布于 2018-10-09 12:28:44
你可以这样做:
$line = Get-Content "<your_log_path>" | Select-String "Validate Domain Credentials" | select -First 1
$regex = '\[(?<domain>[^\\[]+)\\(?<user>[^]]+)\].*time="(?<time>[^"]*)".*date="(?<date>[^"]*)".*component="(?<component>[^"]*)".*context="(?<context>[^"]*)".*type="(?<type>[^"]*)".*thread="(?<thread>[^"]*)".*file="(?<file>[^"]*)"'
if ($line -match $regex) {
$user = $Matches.user
$date = $Matches.date
$time = $Matches.time
# ... now do stuff with your variables ...
}您可能需要构建一些错误检查等(例如,当找不到或不匹配时,等等)。
此外,如果只需要这3个值,则可以大大简化正则表达式。我设计它时,所有的字段都包括在这条线上。
此外,您还可以将值转换为更合适的类型,这可能会使处理它们更容易(取决于以后要对它们做什么):
$type = [int]$Matches.type
$credential = New-Object System.Net.NetworkCredential($Matches.user, $null, $Matches.domain)
$datetime = [DateTime]::ParseExact(($Matches.date + $Matches.time), "MM-dd-yyyyHH:mm:ss.fff+000", [CultureInfo]::InvariantCulture)https://stackoverflow.com/questions/52720923
复制相似问题