【问题标题】:Remove attribute and reformat date string in a file删除文件中的属性并重新格式化日期字符串
【发布时间】:2015-02-04 19:28:37
【问题描述】:

我可以使用以下代码删除该属性。但是,我不知道如何将日期字符串重新格式化为 ISO 格式。从 date="20140424T140222Z" 到 date="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)"
}

}

【问题讨论】:

    标签: powershell powershell-2.0 powershell-3.0 powershell-4.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"
    

    【讨论】:

      【解决方案2】:

      你可以使用.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")
      

      【讨论】:

        猜你喜欢
        • 2019-08-25
        • 1970-01-01
        • 1970-01-01
        • 2015-04-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-09-21
        • 1970-01-01
        相关资源
        最近更新 更多