在此脚本中,我可以获取快捷方式的日期,但采用 YYYYMMDD(和时间)格式。我选择 MM/dd/yyyy。我尝试了网络上的几种建议,但都导致错误,可能是因为字段类型。检查创建、上次修改和安装日期。如果您删除我的日期格式尝试,脚本将正常运行。任何想法都将不胜感激。
$strComputer = "."
$colItems = get-wmiobject -class "Win32_ShortcutFile" -namespace "root\CIMV2" `
-computername $strComputer
foreach ($objItem in $colItems) {
# write-host "Access Mask: " $objItem.AccessMask
# write-host "Archive: " $objItem.Archive
# write-host "Caption: " $objItem.Caption
# write-host "Compressed: " $objItem.Compressed
# write-host "Compression Method: " $objItem.CompressionMethod
# write-host "Creation Class Name: " $objItem.CreationClassName
# write-host "CS Creation Class Name: " $objItem.CSCreationClassName
# write-host "CS Name: " $objItem.CSName
# write-host "Drive: " $objItem.Drive
# write-host "8.3 File Name: " $objItem.EightDotThreeFileName
# write-host "Encrypted: " $objItem.Encrypted
# write-host "Encryption Method: " $objItem.EncryptionMethod
# write-host "Extension: " $objItem.Extension
write-host "File Name: " $objItem.FileName
write-host "Description: " $objItem.Description
write-host "Creation Date: " $objItem.CreationDate -Format 'MM/dd/yyyy'
write-host "File Size: " $objItem.FileSize
write-host "File Type: " $objItem.FileType
# write-host "FS Creation Class Name: " $objItem.FSCreationClassName
# write-host "FS Name: " $objItem.FSName
# write-host "Hidden: " $objItem.Hidden
write-host "Installation Date: " $objItem.InstallDate -Format 'dd/MM/yyyy'
# write-host "In Use Count: " $objItem.InUseCount
write-host "Last Accessed: $objItem.LastAccessed.ToString("MM/dd/yyyy")
write-host "Last Modified: $objItem.LastModified.ToString("MM/dd/yyyy")
# write-host "Manufacturer: " $objItem.Manufacturer
write-host "Name: " $objItem.Name
write-host "Path: " $objItem.Path
# write-host "Readable: " $objItem.Readable
write-host "Status: " $objItem.Status
write-host "System: " $objItem.System
write-host "Target: " $objItem.Target
# write-host "Version: " $objItem.Version
# write-host "Writeable: " $objItem.Writeable
write-host
}
echo "Done"
答案1
发生的情况是,从 WMI 返回的日期/时间戳以字符串的形式返回;
$objItem.CreationDate.GetType().FullName
返回System.String
其类型。
这就是为什么.ToString()
当您尝试将和其他日期格式变体格式化为日期时,它们会失败的原因。
因此,您需要将其从 String 类型转换为 DateTime 类型,然后可以将其转换回(格式化的)String...
方便的是,WMI 对象本身($objItem
在 ForEach 循环中)提供了一种将 WMI 字符串日期/时间戳转换为实际和 System.DateTime 的方法:
$objItem.ConvertToDateTime($objItem.CreationDate)
然后,您可以使用 ToString 将其转换回格式化的字符串。例如:
Write-host "Creation Date: " $objItem.ConvertToDateTime($objItem.CreationDate).ToString('MM\/dd\/yyyy')
确保你转义日期格式字符串中的任何正斜杠,否则 Windows 不会将它们包含在返回的字符串中。