要从今天日期所在的日志中获取文件名,您可以使用以下命令:
$logfile = 'C:\Creds\AzCopyVerbose.log'
$today = Get-Date -UFormat "%Y/%m/%d"
$pattern = '^\[(?<date>\d{4}/\d{2}/\d{2}).*Finished transfer:\s+(?<filename>.*)\s+=>.*$'
Select-String -Path $logfile -Pattern $pattern | Select-Object -Last 20 | ForEach-Object {
$null = $_.Line -match $pattern
if ($matches['date'] -eq $today) {
Write-Host $matches['filename']
}
else {
Write-Host "The date present in the azcopy verbose log is older"
}
}
除了使用Select-String,你也可以这样做,它只需要匹配一次模式,所以在我看来更简洁:
$logfile = 'C:\Creds\AzCopyVerbose.log'
$today = Get-Date -UFormat "%Y/%m/%d"
$pattern = '^\[(?<date>\d{4}/\d{2}/\d{2}).*Finished transfer:\s+(?<filename>.*)\s+=>.*$'
Get-Content -Path $logfile | Select-Object -Last 20 | Where-Object { $_ -match $pattern } | ForEach-Object {
if ($matches['date'] -eq $today) {
Write-Host $matches['filename']
}
else {
Write-Host "The date present in the azcopy verbose log is older"
}
}
附言我使用Get-Date -UFormat "%Y/%m/%d",因为(Get-Date).ToString('yyyy/MM/dd') 在我的荷兰机器上输出2018-11-10
正则表达式详细信息
^ Assert position at the beginning of the string
\[ Match the character “[” literally
(?<date> Match the regular expression below and capture its match into backreference with name “date”
\d Match a single digit 0..9
{4} Exactly 4 times
\/ Match the character “/” literally
\d Match a single digit 0..9
{2} Exactly 2 times
\/ Match the character “/” literally
\d Match a single digit 0..9
{2} Exactly 2 times
)
. Match any single character that is not a line break character
* Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
Finished\ transfer: Match the characters “Finished transfer:” literally
\s Match a single character that is a “whitespace character” (spaces, tabs, line breaks, etc.)
+ Between one and unlimited times, as many times as possible, giving back as needed (greedy)
(?<filename> Match the regular expression below and capture its match into backreference with name “filename”
. Match any single character that is not a line break character
* Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
)
\s Match a single character that is a “whitespace character” (spaces, tabs, line breaks, etc.)
+ Between one and unlimited times, as many times as possible, giving back as needed (greedy)
=> Match the characters “=>” literally
. Match any single character that is not a line break character
* Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
$ Assert position at the end of the string (or before the line break at the end of the string, if any)