使用 powershell Get-Content 从文本文件中读取日期和时间

Reading date and time from a text file using powershell Get-Content

我有一个包含日志文件的最后更新的文本文件。

 Volume in drive E is ISCSI
 Volume Serial Number is XXXXXX

 Directory of E:\Apps\LOGS

02/26/2020  11:39 AM           762,661-vx_02262020.log
               1 File(s)        762,661 bytes
               0 Dir(s)  12,554,166,272 bytes free

我正在使用下面的 powershell 脚本来阅读内容并通过电子邮件发送相同内容:

$Date = (Get-Date -format "MMddyyyy")

$body = Get-Content -path C:\Desktop\Logs\LOG_TIME_$Date.txt -raw

Send-MailMessage -To "abc@gmail.com2" -From "abc@gmail.com"  -Subject "LOG TIME $Date" -Body "$body" -SmtpServer "xxxxx.main.glb.corp.local"

代码工作正常,并将正文中文件的所有内容发送到我的电子邮件。但我只希望在电子邮件中发送日期和时间(会不断变化)。

我尝试了很多选项,但 none 似乎可行:

有人可以帮助我如何从文本文件中仅在电子邮件正文中填充日期和时间吗?

要解析文件中的日期和时间,您可以使用:

$Date = (Get-Date -format "MMddyyyy")

$content = Get-Content -Path "C:\Desktop\Logs\LOG_TIME_$Date.txt" -Raw
if ($content -match '(\d{2}/\d{2}/\d{4}\s+\d{1,2}:\d{2}\s+[AP]M)') {
    $dateString = $matches[1] -replace '\s+', ' '
    $dateInFile = [DateTime]::ParseExact($dateString, 'MM/dd/yyyy h:mm tt', [cultureinfo]'en-UK')
}

$mailParams = @{
    To         = "abc@gmail.com"
    From       = "abc@gmail.com"
    Subject    = "LOG TIME $Date"
    Body       = $dateInFile
    SmtpServer = "xxxxx.main.glb.corp.local"
}

Send-MailMessage @mailParams

正则表达式详细信息:

(             # Match the regular expression below and capture its match into backreference number 1
   \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 the character "/" literally
   \d         # Match a single digit 0..9
      {4}     # Exactly 4 times
   \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)
   \d         # Match a single digit 0..9
      {1,2}   # Between one and 2 times, as many times as possible, giving back as needed (greedy)
   :          # Match the character ":" literally
   \d         # Match a single digit 0..9
      {2}     # Exactly 2 times
   \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)
   [AP]       # Match a single character present in the list "AP"
   M          # Match the character "M" literally
)

使用正则表达式轻松完成:

$date = $content | ? { $_ -match '(\d{1,2}\/\d{1,2}\/\d{2,4})' } | % { $_ -replace '^(.*)(\d{1,2}\/\d{1,2}\/\d{2,4})(.*)$', '' }