[英]check if datetime exists in a string powershell
Im a complete powershell beginner.我是一个完整的 powershell 初学者。 I have to read a log file and check if the last entry is of current time stamp.我必须读取日志文件并检查最后一个条目是否具有当前时间戳。
I have fetched last line using Get-Content;我使用 Get-Content 获取了最后一行;
PS> Write-Host $lastLine
new levels are 10/12/2016 4:23:34 PM
PS> $x =Get-Date
PS> Write-Host $x
10/12/2016 4:23:34 PM
I've tried using -match as well as -contains while regex,casting param to string etc., but to no avail我试过在正则表达式中使用 -match 和 -contains,将参数转换为字符串等,但无济于事
1.PS C:\Users\xxx> $y = $lastLine -Match [regex]::escape($x)
2.PS C:\Users\xxx> $y=$lastLine -contains $x
and few other, PN: checked $y value after each of above case.和其他一些,PN:在上述每个案例之后检查 $y 值。 $y is returning false., can anyone guide me to a reference/solution. $y 返回 false。,任何人都可以指导我参考/解决方案。 I'm missing something here我在这里遗漏了一些东西
If you have a formatted date string stored in the variable $formattedDate
you can test if the line ends with a space followed by that date string using...如果您将格式化的日期字符串存储在变量$formattedDate
您可以测试该行是否以空格结尾,后跟该日期字符串,使用...
$lastLine -like "* $formattedDate";
Remember that the Get-Date
cmdlet returns a DateTime
value, not a string
.请记住, Get-Date
cmdlet 返回DateTime
值,而不是string
。 When you use operators such as -like
or -match
to search for a date in a specific format, you'll want to ensure that your date variable gets formatted the way you expect it to.当您使用运营商,如-like
或-match
来搜索特定格式的日期,你要确保你的约会变量被格式化你希望它的方式。 That is, don't rely on the default, culture-specific date formatting but rather specify exactly what you need:也就是说,不要依赖于默认的、特定于文化的日期格式,而是确切地指定您需要的内容:
$date = Get-Date;
$formattedDate = $date.ToString('MM/dd/yyyy h:mm:ss tt');
if ($lastLine -like "* $formattedDate")
{
# ...
}
You can combine the first two lines into one using the -Format
parameter:您可以使用-Format
参数将前两行合并为-Format
:
$formattedDate = Get-Date -Format 'MM/dd/yyyy h:mm:ss tt';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.