我可以使用以下代码删除该属性。但是,我不知道如何将日期字符串重新格式化为ISO格式。从日期=" 20140424T140222Z "到目前为止=" 2014-04-24T14:02:22Z "
function update {
$unzippedLocation = Get-ChildItem $destination -Recurse
# from date="20140424T140222Z" to date="2014-04-24T14:02:22Z"
Message "Remove and reformat attributes"
$regex='date="(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z"'
ForEach($unzippedFile in $unzippedLocation) {
(Get-Content $unzippedFile) |
ForEach-Object { $_ -replace ' crc=""', '' } |
ForEach-Object { $_ -replace $regex, 'date="$1-$2-$3T$4:$5:$6Z"' } |
Set-Content $unzippedFile
Write-Host "crc attribute has been removed from $($unzippedFile.Name)"
Write-Host "date attribute has been reformated from $($unzippedFile.Name)"
}
}
答案 0 :(得分:1)
我不完全明白你需要更换日期,但一种方法是使用正则表达式来更新日期。以下是一个字符串的示例,您可以将其合并到您需要的位置:
#Defines regex with a separate group for each component
$regex='date="(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z"'
#Sample input
$input = 'date="20140424T140222Z"'
#Update the string
$result = $input -replace $regex, 'date="$1-$2-$3T$4:$5:$6Z"'
Write-Host $result
#Result is
#date="2014-04-24T14:02:22Z"
答案 1 :(得分:1)
您可以使用.net方法TryParseExact。
此方法将尝试解析有效DateTime值中的任何字符串,然后再格式化为ISO格式。使用此方法可以测试您的值是否有效。
示例:
$dateString = "20140424T140222Z"
$format = "yyyyMMddTHHmmssZ"
[ref]$parsedDate = get-date
$parsed = [DateTime]::TryParseExact($dateString, $format,[System.Globalization.CultureInfo]::InvariantCulture,[System.Globalization.DateTimeStyles]::None,$parseddate)
if($parsed)
{
write "$dateString is valid"
}
$parseddate.Value.ToString("yyyy-MM-ddTHH:mm:ssZ")