首页 > 解决方案 > Powershell 选择字符串

问题描述

我需要你对 PowerShell 的帮助。

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

但我也需要选择日期低于我在变量中写入的字符串。

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

标签: powershellselect-string

解决方案


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


推荐阅读