AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / computer / 问题 / 1626548
Accepted
LCIII
LCIII
Asked: 2021-02-17 09:01:34 +0800 CST2021-02-17 09:01:34 +0800 CST 2021-02-17 09:01:34 +0800 CST

在PowerShell中将字符串转换为格式化的日期时间时出错“字符串未被识别为有效的日期时间”

  • 772

我以Media Created这种方式从文件资源管理器中检索列字段:

$mCreated = $shellfolder.GetDetailsOf($shellfile, 208);

这很好用。它给了我字符串“5/‎7/‎2017 ‏‎4:09 PM”

问题:

当我尝试将字符串转换为格式化日期时,出现此错误:

Exception calling "ParseExact" with "3" argument(s): "String was not recognized as a valid DateTime."
At C:\Client\testVideos\anotherTest.ps1:28 char:9
+         $formattedDate = [Datetime]::ParseExact("$mCreated".Trim(), ' ...
+         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : FormatException

我试过的:

分别尝试了这些,都给了我同样的错误:

$formattedDate = [Datetime]::ParseExact("$mCreated".Trim(), 'yyyyMMddTHHmmss', $null)
$formattedDate = [Datetime]::ParseExact("$mCreated".Trim(), 'yyyyMMddTHHmmss', [Globalization.CultureInfo]::InvariantCulture)

# This line actually gives me a different error
$formattedDate = Get-Date "$mCreated".Trim() -Format "yyyyMMddTHHmmss"

# ERROR: Get-Date : The input object cannot be bound to any parameters for the command either because the command does not take pipeline input or the input and its properties do not match any of the parameters that take pipeline input

什么有效:

我也一直Created Date在使用相同的代码并以相同的方式对其进行格式化,并且它有效!

创建日期为“2/12/2021 1:10 PM”、“2/4/2021 3:39 PM”、“2/2/2021 9:00 AM”或“2/4/2021 3:54”下午”

# This formats it successfully with no error
$createdDate = $shellfolder.GetDetailsOf($shellfile, 4);
$formattedDate = $createdDate | Get-Date -Format "yyyyMMddTHHmmss"

相关但最终无济于事:

https://stackoverflow.com/questions/42784919/parseexact-string-was-not-recognized-as-a-valid-datetime https://stackoverflow.com/questions/48637312/convert-string-to-powershell-datetime

powershell powershell-ise
  • 2 2 个回答
  • 2374 Views

2 个回答

  • Voted
  1. Best Answer
    Keith Miller
    2021-02-17T13:15:53+08:002021-02-17T13:15:53+08:00

    I had the same issue in the past with various dates returned by the Folder.GetDetailsOf() method. I found the issue to be Unicode formatting characters

    PS C:\> $TestFile = 'C:\Users\keith\Music\ABBA\Hits\03 Dancing Queen.wma'
    
    >> $ofolder  = $Shell.NameSpace((Split-Path $TestFIle))
    >> $oFile    = $oFolder.ParseName((Split-Path $TestFile -Leaf))
    >>
    >> $MediaCreated = $oFolder.GetDetailsOf($oFile, 208)
    >> $MediaCreated
    >> $MediaCreated.Length
    >> [Int[]][Char[]]$MediaCreated -join '-'
    >>
    ‎6/‎19/‎2010 ‏‎11:54 PM
    23
    8206-54-47-8206-49-57-47-8206-50-48-49-48-32-8207-8206-49-49-58-53-52-32-80-77
    PS C:\>>[DateTime]$MediaCreated
    Cannot convert value "‎6/‎19/‎2010 ‏‎11:54 PM" to type "System.DateTime". Error:
    "String was not recognized as a valid DateTime."
    At line:1 char:1
     + [DateTime]$MediaCreated
     + ~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : InvalidArgument: (:) [], RuntimeException
        + FullyQualifiedErrorId : InvalidCastParseTargetInvocationWithFormatProvider
    

    My solution was to "whitelist" valid DateTime characters in a regualr expression. So the regex matches for "good" characters are:

    • \w Any word character (0..9, 'A', 'P', and 'M')
    • \: Colons (Time separator)
    • / Slashes (Date separator)
    • Spaces

    Separators may vary based on region. I'm hard-coding for U.S. for simplicity, brevity, and laziness.

    These can be combined & enclosed in brackets to create a character class that will match valid characters.:

    • [\w\:/ ]

    To invert the class, & match invalid characters, prepend a caret to the class definition:

    • [^\w\:/ ]

    Then we can use the -Replace operator to remove them:

    • [DateTime]($MediaCreated -replace '[^\w\:/ ]','')
    PS C:\> $MediaCreated = [DateTime]($MediaCreated -replace '[^\w\:/ ]','')
    PS C:\>>$MediaCreated
    
    Saturday, June 19, 2010 11:54:00 PM
    
    
    PS C:\>>$MediaCreated.GetType()
    
    IsPublic IsSerial Name                                     BaseType
    -------- -------- ----                                     --------
    True     True     DateTime                                 System.ValueType
    

    Just recently learned of the alternative: ShellFolderItem.ExtendedProperty()

    Gets the value of a property from an item's property set. The property can be specified either by name or by the property set's format identifier (FMTID) and property identifier (PID).

    Return value Type: Variant*

    When this method returns, contains the value of the property, if it exists for the specified item. The value will have full typing—for example, dates are returned as dates, not strings.

    This method returns a zero-length string if the property is valid but does not exist for the specified item, or an error code otherwise.

    Remarks There are two ways to specify a property. The first is to assign the property's well-known name, such as "Author" or "Date", to sPropName. However, each property is a member of a Component Object Model (COM) property set and can also be identified by specifying its format ID (FMTID) and property ID (PID). An FMTID is a GUID that identifies the property set, and a PID is an integer that identifies a particular property within the property set.

    通过其 FMTID/PID 值指定属性通常比使用其名称更有效。要将属性的 FMTID/PID 值与 ExtendedProperty 一起使用,必须将它们组合成一个 SCID。SCID 是一个字符串,其中包含格式为“FMTID**PID”的 FMTID/PID 值,其中 FMTID 是属性集 GUID 的字符串格式。例如,摘要信息属性集的作者属性的SCID为“{F29F85E0-4FF9-1068-AB91-08002B27B3D9} 4”。

    我找不到“Media Created”的正确名称,但 * FMTID/PID* 对是"{2E4B640D-5019-46D8-8881-55414CC5CAA0}100":

    PS C:\>>$oFile.ExtendedProperty("MediaCreated")
    PS C:\> $oFile.ExtendedProperty("Media Created")
    PS C:\> $oFile.ExtendedProperty("MediaEncoded")
    PS C:\> $oFile.ExtendedProperty("MediaCreationDate")
    PS C:\> $oFile.ExtendedProperty("System.MediaEncoded")
    PS C:\>>$oFile.ExtendedProperty("{2E4B640D-5019-46D8-8881-55414CC5CAA0}100")
    
    Sunday, June 20, 2010 04:54:26 AM
    
    
    PS C:\>>($oFile.ExtendedProperty("{2E4B640D-5019-46D8-8881-55414CC5CAA0}100")).GetType()
    
    IsPublic IsSerial Name                                     BaseType
    -------- -------- ----                                     --------
    True     True     DateTime                                 System.ValueType
    
    
    • 4
  2. postanote
    2021-02-17T12:55:15+08:002021-02-17T12:55:15+08:00

    继续我的评论,顺便说一句,你也可以这样做来格式化。

    ($mCreated = (Get-Date -Format g).ToString())
    # Results
    <#
    2/16/2021 11:10 AM
    #>
    
    ($mCreated).GetType() | 
    Format-Table -AutoSize
    # Results
    <#
    IsPublic IsSerial Name   BaseType     
    -------- -------- ----   --------     
    True     True     String System.Object
    #>
    
    $mCreated | 
    Get-Member
    # Results
    <#
    TypeName: System.String
    
    Name             MemberType            Definition                                                                                                     
    ----             ----------            ----------                                                                                                     
    ...                                                                     
    Chars            ParameterizedProperty char Chars(int index) {get;}                                                                                   
    Length           Property              int Length {get;} 
    #> 
    
                                                                                            
    

    将日期字符串转换为日期时间对象

    ([DateTime]$mCreated = ((Get-Date -Format g).ToString()))
    # Results
    <#
    Tuesday, February 16, 2021 11:12:00 AM
    #>
    
    ($mCreated).GetType() | 
    Format-Table -AutoSize
    # Results
    <#
    IsPublic IsSerial Name     BaseType        
    -------- -------- ----     --------        
    True     True     DateTime System.ValueType
    #>
    
    $mCreated | 
    Get-Member
    # Results
    <#
    TypeName: System.DateTime
    
    Name                 MemberType     Definition                                                                                                        
    ----                 ----------     ----------                                                                                                        
    ...                                                    
    ToUniversalTime      Method         datetime ToUniversalTime()                                                                                        
    Date                 Property       datetime Date {get;}                                                                                              
    Day                  Property       int Day {get;}                                                                                                    
    DayOfWeek            Property       System.DayOfWeek DayOfWeek {get;}                                                                                 
    DayOfYear            Property       int DayOfYear {get;}                                                                                              
    Hour                 Property       int Hour {get;}                                                                                                   
    Kind                 Property       System.DateTimeKind Kind {get;}                                                                                   
    Millisecond          Property       int Millisecond {get;}                                                                                            
    Minute               Property       int Minute {get;}                                                                                                 
    Month                Property       int Month {get;}                                                                                                  
    Second               Property       int Second {get;}                                                                                                 
    Ticks                Property       long Ticks {get;}                                                                                                 
    TimeOfDay            Property       timespan TimeOfDay {get;}                                                                                         
    Year                 Property       int Year {get;}                                                                                                   
    DateTime             ScriptProperty System.Object DateTime {get=if ((& { Set-StrictMode -Version 1; $this.DisplayHint }) -ieq  "Date")... 
    #>
    

    详细信息和更多信息:

    • https://adamtheautomator.com/demystifying-powershell-dates-datetime-and-formatting
    • https://adamtheautomator.com/powershell-conver-string-date-casting/#Converting_a_String_to_a_Date
    • http://winpowershell.blogspot.com/2006/09/systemdatetime-parseexact.html#!/2006/09/systemdatetime-parseexact.html
    • http://powershell.com/cs/blogs/tips/archive/2013/02/07/parsing-custom-date-and-time-formats.aspx

    至于带有 parseexact 的字符串。它受系统日期设置方式的影响,并且 yeat 必须位于时间戳的开头或结尾。在此处查看详细信息:

    [datetime]::ParseExact("20181010134412",'yyyyMMddHHmmss',$null)
    # Results
    <#
    Wednesday, October 10, 2018 1:44:12 PM
    #>
    
    ($mCreated).GetType() | 
    Format-Table -AutoSize
    # Results
    <#
    IsPublic IsSerial Name   BaseType     
    -------- -------- ----   --------     
    True     True     String System.Object
    #>
    
    [datetime]::ParseExact($mCreated,'yyyyMMddHHmmss',$null)
    [datetime]::ParseExact($($mCreated),'yyyyMMddHHmmss',$null)
    # Results
    <#
    Exception calling "ParseExact" with "3" argument(s): "String was not recognized as a valid DateTime."
    #>
    
    $mCreated
    # Results
    <#
    2/16/2021 11:24 AM
    #>
    
    [datetime]::ParseExact('20210216112400','yyyyMMddHHmmss',$null)
    [datetime]::ParseExact('02161124002021','MMddHHmmssyyyy',$null)
    # Results
    <#
    Tuesday, February 16, 2021 11:24:00 AM
    Tuesday, February 16, 2021 11:24:00 AM
    #>
    

    或者你最终在这里:

    $mCreated = '16/02/2021 9:11 AM'
    ([datetime]::ParseExact($mCreated,'dd/MM/yyyy h:mm tt',$null))
    $mCreated = '02/16/2021 9:11 AM'
    ([datetime]::ParseExact($mCreated,'MM/dd/yyyy h:mm tt',$null))
    # Results
    <#
    Tuesday, February 16, 2021 9:11:00 AM
    Tuesday, February 16, 2021 9:11:00 AM
    #>
    

    在此处查看详细信息:

    • https://lazywinadmin.com/2018/10/PowerShellTip-DateTimeParsing.html

    无法打印/不可见的字符是尝试使用调用中的日期字符串时的问题。

    $FileInformation    = Get-ItemProperty -Path 'F:\Videos\2020 03 19 Competitive Intel.mp4'
    $ShellApplication   = New-Object -ComObject Shell.Application
    
    $ShellFolder        = $ShellApplication.Namespace($FileInformation.Directory.FullName)
    $ShellFile          = $ShellFolder.ParseName($FileInformation.Name)
    
    $MetaDataProperties = [ordered] @{}
    
    0..400 | 
    ForEach-Object -Process {
        $DataValue     = $ShellFolder.GetDetailsOf($null, $_)
        $PropertyValue = (Get-Culture).TextInfo.ToTitleCase($DataValue.Trim()).Replace(' ', '')
    
        if ($PropertyValue -ne '') 
        {$MetaDataProperties["$_"] = $PropertyValue}
    }
    
    $MetaDataProperties.Values -Match 'media'
    # Results
    <#
    MediaCreated
    #>
    
    ###
    ($MediaCreated = $ShellFolder.GetDetailsOf($ShellFile , 208))
    ($DateCreated  = $ShellFolder.GetDetailsOf($ShellFile , 4))
    ($MediaCreated).GetType()
    ($DateCreated).GetType()
    # Results
    <#
    19-‎Mar-‎20 ‏‎17:30
    03-Dec-20 13:05
    
    IsPublic IsSerial Name    BaseType
    -------- -------- ----    --------
    True     True     String  System.Object
    True     True     String  System.Object
    #>
    
    
    ($TestDate = Get-Date(Date) -Format g) 
    ($TestDate1 = Get-Date(Date) -Format g) -replace '-|\s|:'
    # Results
    <#
    17-Feb-21 16:41
    17Feb211641
    #>
    
    ([datetime]::ParseExact($TestDate,'dd-MMM-yy HH:mm',$null))
    ([datetime]::ParseExact($TestDate1,'dd-MMM-yy HH:mm',$null))
    # Results
    <#
    Wednesday, 17 February, 2021 16:54:00
    Wednesday, 17 February, 2021 16:54:00
    #>
    
    (('17-Feb-21 16:41').ToCharArray()).Count
    # Results
    <#
    15
    #>
    
    
    ([datetime]::ParseExact($MediaCreated,'dd-MMM-yy HH:mm',$null))
    # Results
    <#
    Exception calling "ParseExact" with "3" argument(s): "String was not recognized 
    as a valid DateTime."
    #>
    

    在常规 cmd.exe(不是来自 PowerShell (ISE/consolehost) 或通过 Windows 终端的 cmd.exe)中,Notepad/consolehost/ISE/VSCode/Windows 终端中没有出现无法打印/不可见的字符。

    在此处输入图像描述

    (($MediaCreated).ToCharArray()).Count
    # Results
    <#
    20  # multiple hidden/non-printable characters
    #>
    
    ($MediaCreated).ToCharArray() 
    # Results
    <#
    1
    9
    -
    ‎
    M
    a
    r
    -
    ‎
    2
    0
    
    ‏
    ‎
    1
    7
    :
    3
    0 
    
    #>
    
    (($MediaCreated).ToCharArray())[0]
    (($MediaCreated).ToCharArray())[1]
    (($MediaCreated).ToCharArray())[2]
    (($MediaCreated).ToCharArray())[3]
    # Results
    <#
    1
    9
    -
    
    #>
    
    ($MediaCreated).ToCharArray() | 
    ForEach{ [int][char]$PSItem }
    # Results
    <#
    8206
    49
    57
    45
    8206
    77
    97
    114
    45
    8206
    50
    48
    32
    8207
    8206
    49
    55
    58
    51
    48
    #>
    

    因此,为什么基思的正则表达式有效......

    ([datetime]::ParseExact(($MediaCreated -replace '[^\w\:/ ]'),'ddMMMyy HH:mm',$null))
    # Results
    <#
    Thursday, 19 March, 2020 17:30:00
    #>
    

    ...因此我们可以更直接地获取它,以允许 parseexact 工作,而不必更改数据类型:

    $FileInformation  = Get-ItemProperty -Path 'F:\Videos\2020 03 19 Competitive Intel.mp4'
    $ShellApplication = New-Object -ComObject Shell.Application
    
    $ShellFolder      = $ShellApplication.Namespace($FileInformation.Directory.FullName)
    $ShellFile        = $ShellFolder.ParseName($FileInformation.Name)
    
    ($MediaCreated    = $ShellFolder.GetDetailsOf($ShellFile , 208))
    ($DateCreated     = $ShellFolder.GetDetailsOf($ShellFile , 4))
    # Results
    <#
    ‎19-‎Mar-‎20 ‏‎17:30
    03-Dec-20 13:05
    #>
    
    ($MediaCreated).GetType()
    ($DateCreated).GetType()
    
    # Results
    <#
    IsPublic IsSerial Name     BaseType     
    -------- -------- ----     --------     
    True     True     String   System.Object
    True     True     String   System.Object 
    #>        
    
    ([datetime]::ParseExact(($MediaCreated -replace '[^\w\:/ ]'),'ddMMMyy HH:mm',$null))
    ([datetime]::ParseExact(($DateCreated -replace '[^\w\:/ ]'),'ddMMMyy HH:mm',$null))
    # Results
    <#
    
    Thursday, 19 March, 2020 17:30:00
    Thursday, 3 December, 2020 13:05:00
    #>
    
    ($MediaCreated).GetType()
    ($DateCreated).GetType()
    # Results
    <#
    
    IsPublic IsSerial Name     BaseType     
    -------- -------- ----     --------     
    True     True     String   System.Object
    True     True     String   System.Object 
    #>
    
    • 1

相关问题

  • 如何将变量字符串放入powershell中的数组?

  • Powershell 和正则表达式:Notepad++“保存时备份”文件列表。编辑名称,按上次写入时间排序

  • 将前景颜色添加到 Powershell 配置文件?

  • 禁用后无法启用 Microsoft Print to PDF

  • 我可以让这个 PowerShell 脚本接受逗号吗?

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    如何减少“vmmem”进程的消耗?

    • 11 个回答
  • Marko Smith

    从 Microsoft Stream 下载视频

    • 4 个回答
  • Marko Smith

    Google Chrome DevTools 无法解析 SourceMap:chrome-extension

    • 6 个回答
  • Marko Smith

    Windows 照片查看器因为内存不足而无法运行?

    • 5 个回答
  • Marko Smith

    支持结束后如何激活 WindowsXP?

    • 6 个回答
  • Marko Smith

    远程桌面间歇性冻结

    • 7 个回答
  • Marko Smith

    子网掩码 /32 是什么意思?

    • 6 个回答
  • Marko Smith

    鼠标指针在 Windows 中按下的箭头键上移动?

    • 1 个回答
  • Marko Smith

    VirtualBox 无法以 VERR_NEM_VM_CREATE_FAILED 启动

    • 8 个回答
  • Marko Smith

    应用程序不会出现在 MacBook 的摄像头和麦克风隐私设置中

    • 5 个回答
  • Martin Hope
    Saaru Lindestøkke 为什么使用 Python 的 tar 库时 tar.xz 文件比 macOS tar 小 15 倍? 2021-03-14 09:37:48 +0800 CST
  • Martin Hope
    CiaranWelsh 如何减少“vmmem”进程的消耗? 2020-06-10 02:06:58 +0800 CST
  • Martin Hope
    Jim Windows 10 搜索未加载,显示空白窗口 2020-02-06 03:28:26 +0800 CST
  • Martin Hope
    v15 为什么通过电缆(同轴电缆)的千兆位/秒 Internet 连接不能像光纤一样提供对称速度? 2020-01-25 08:53:31 +0800 CST
  • Martin Hope
    andre_ss6 远程桌面间歇性冻结 2019-09-11 12:56:40 +0800 CST
  • Martin Hope
    Riley Carney 为什么在 URL 后面加一个点会删除登录信息? 2019-08-06 10:59:24 +0800 CST
  • Martin Hope
    zdimension 鼠标指针在 Windows 中按下的箭头键上移动? 2019-08-04 06:39:57 +0800 CST
  • Martin Hope
    jonsca 我所有的 Firefox 附加组件突然被禁用了,我该如何重新启用它们? 2019-05-04 17:58:52 +0800 CST
  • Martin Hope
    MCK 是否可以使用文本创建二维码? 2019-04-02 06:32:14 +0800 CST
  • Martin Hope
    SoniEx2 更改 git init 默认分支名称 2019-04-01 06:16:56 +0800 CST

热门标签

windows-10 linux windows microsoft-excel networking ubuntu worksheet-function bash command-line hard-drive

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve