PowerShell 中的 [datetime]::ParseExact 问题

问题描述 投票:0回答:1

我正在尝试更新here找到的脚本以使用 Office 365 导出的日历条目。

我更改了 DTSTART 和 DTEND 的变量(或者更确切地说我正在尝试),因为新的 ICS 文件显示的格式为

DTEND;TZID="W. Europe Standard Time":20240111T160000
DTSTART;TZID="W. Europe Standard Time":20240111T150000

我的修改是

    $DSTART = ($data.GetEnumerator() | ?{ $_.Name -eq 'DSTART;TZID=\"W. Europe Standard Time\"' }).Value -replace "T"
    $DSTART = [datetime]::ParseExact($DSTART, "yyyyMMddHHmmss", $null)

    $DTEND = ($data.GetEnumerator() | ?{ $_.Name -eq 'DTEND;TZID=\"W. Europe Standard Time\"' }).Value -replace "T"
    $DTEND = [datetime]::ParseExact($DTEND, "yyyyMMddHHmmss", $null)

但是,我越来越

Exception calling "ParseExact" with "3" argument(s): "String was not recognized as a valid DateTime."
At line:28 char:5
+     $DSTART = [datetime]::ParseExact($DSTART, "yyyyMMddHHmmss", $null ...
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : FormatException
 
Exception calling "ParseExact" with "3" argument(s): "String was not recognized as a valid DateTime."
At line:31 char:5
+     $DTEND = [datetime]::ParseExact($DTEND, "yyyyMMddHHmmss", $null)
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : FormatException

有人知道我哪里出错了吗?

谢谢您的帮助:) 亚历克斯

powershell datetime
1个回答
0
投票
  • 您当前的问题是不必要地尝试转义

    "
    字符。 as
    \"
    :在逐字 PowerShell 字符串文字 (
    '...'
    ) 中,
    "
    不需要转义(在可扩展字符串
    "..."
    中,您需要
    `"
    (或
    ""
    )-
    \ 
    not 是否用作转义字符。在 PowerShell 中,只有
    `
    (所谓的反引号)可以。

  • 但是,您的代码可以简化(就像链接帖子中的代码一样);见下文。

# Convert the file lines into a hashtable (key-value pairs)
$data = @{}
@'
DTEND;TZID="W. Europe Standard Time":20240111T160000
DTSTART;TZID="W. Europe Standard Time":20240111T150000
'@ -split '\r?\n' | 
  ForEach-Object {
    $key, $value = $_ -split ':', 2
    $data[$key] = $value
  }

# Access the entries of interest by key and parse them as dates.
$dStart = [datetime]::ParseExact(
  $data['DTSTART;TZID="W. Europe Standard Time"'], 
  'yyyyMMddTHHmmss', 
  $null)

$dEnd = [datetime]::ParseExact(
  $data['DTEND;TZID="W. Europe Standard Time"'],
  'yyyyMMddTHHmmss', 
  $null)

# Sample output of the result.
[pscustomobject] @{
  Start = $dStart
  End = $dEnd
}
© www.soinside.com 2019 - 2024. All rights reserved.