Powershell选择字符串

问题描述

我需要您在PowerShell方面的帮助。

我需要带固定日期的Select-String(在变量中)。 &将内容设置为result.txt 示例:$Date = "01.07.2020"

但是我还需要选择日期比写在变量中的日期短的字符串。

我的代码Get-Content -Path log.txt | Select-String "?????" | Set-Content $result.txt

  • 在log.txt中,我有很多字符串,例如“ Creation date 01.07.2020”; “创建日期01.06.2020“

解决方法

123.txt

Creation date 01.07.2020
Creation date 02.05.2020
Creation date 01.06.2020
Creation date 28.08.2020

示例脚本

$file = "C:\Users\userprofile\Desktop\test\123.txt"
$regexpattern = "\d{2}\.\d{2}\.\d{4}"
$content = Get-Content $file | Where-object { $_ -match $regexpattern}

foreach($line in $content){

    $line.Substring(13,11)

}

我使用了正则表达式来查找要输出的行。仅当内容与正则表达式匹配时,我们才能获取内容,然后对于找到的每一行,我都使用子字符串来提取日期。如果需要,您也可以为此使用正则表达式。由于我们知道这些行具有相同数量的字符,因此可以安全地使用substring函数。

如果要将输出输出到文件中,只需找到$line.Substring(13,11),然后将其添加到| Out-file "C:\Users\userprofile\desktop\test\output.txt" -append之后。