regex - 在正则表达式替换中转换日期时间

标签 regex powershell

我使用的是 PS 版本 5.1.23560.1000


让我们有一个简单的 input.txt 文件,如下所示:

@{Name=file1.txt; LastAccessTime=10/22/2023 6:59:16 PM}
@{Name=file2.txt; LastAccessTime=10/22/2023 6:59:22 PM}

我想显示日期时间后跟文件名,但我想将日期时间转换为 yyyyMMddHHmmss 格式。

所以我将使用这种类型的日期时间转换(示例):

PS> ([datetime]'10/22/2023 6:59:16 PM').ToString('yyyyMMddHHmmss')
20231022185916

太棒了!


为了获得所需的输出,我使用了:

Get-Content 'input.txt' | % { $_ -replace '^.*=(.*); Last\w+Time=(.*)}.*$', ($(([datetime]'$2').ToString('yyyyMMddHHmmss')) + "`t" + '$1') }

不幸的是,而不是

20231022185916   file1.txt
20231022185922   file2.txt

我得到了这个:

Cannot convert value "$2" to type "System.DateTime". Error: "String was not recognized as a valid DateTime."
At line:1 char:102
+ ... ime=(.*)}.*$', ($(([datetime]'$2').ToString('yyyyMMddHHmmss')) + "`t" ...
+                       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvalidCastParseTargetInvocationWithFormatProvider

        file1.txt
Cannot convert value "$2" to type "System.DateTime". Error: "String was not recognized as a valid DateTime."
At line:1 char:102
+ ... ime=(.*)}.*$', ($(([datetime]'$2').ToString('yyyyMMddHHmmss')) + "`t" ...
+                       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvalidCastParseTargetInvocationWithFormatProvider

        file2.txt

我做错了什么?正确的语法应该是什么?

请注意,我必须使用-replace,因为我的问题比这个简单的演示更复杂。

最佳答案

没有完全忽略 Avoiding the use of Invoke-Expression 上的大量文章,它为您在考虑评论时遇到的紧迫问题提供了快速解决方案。

由于哈希表不会采用某些 as-is 的值,因此您必须引用它们,以便将它们全部列出作为类型[string]。话虽如此,您可以使用以下模式来获取引用的分组,这将是您的值:

(?<==)(.+?)(?=;|})','"$1"'

这只是允许在需要时进行进一步的类型转换

$hashtable = Invoke-Expression -Command ($_ -replace '(?<==)(.+?)(?=;|})','"$1"')
'{0} {1}' -f ([datetime]$hashtable['LastAccessTime']).ToString('yyyyMMddHHmmss'), $hashtable['Name']

如果对 Invoke-Expression 的使用有任何疑问,您始终可以使用不同的方法,例如 ConvertFrom-StringData:

$hashtables = 
    Get-Content 'input.txt' | 
    % { 
        ($_ -replace "@{|}", "") -replace ";", "`n" | ConvertFrom-StringData 
    }

'{0} {1}' -f ([datetime]$hashtables[0]['LastAccessTime']).ToString('yyyyMMddHHmmss'), $hashtables[0]['Name']

关于regex - 在正则表达式替换中转换日期时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77347984/

相关文章:

c# - 你能改进这个 C# 正则表达式代码吗?

python - 我如何表示此正则表达式不会出现 "bad character range"错误?

javascript - 键入时验证电子邮件

regex - 在 PowerShell/PowerCLI 中将前缀附加到字符串

powershell - 运算符 '-gt' 在此 PowerShell 中不起作用

powershell - 完全没有输出的Powershell中的最终过程

python - 具有反向引用的 re.sub

regex - 识别哈希键的 "type"

PowerShell - 将属性名称从 Pascal 大小写转换为带下划线的大写

asp.net - 是否可以从 ASP MVC 项目执行 Azure PowerShell 脚本?