如何删除Powershell中的表头并转换为日期类型?

问题描述

嘿,我正在尝试创建一个脚本来从 excel 中提取数据并将其插入到 sql 中。

当我提取日期值并且它们成为表格的一部分时,问题就出现了,每当我尝试使用以下代码时,我都会在这文章底部收到错误消息。提取并转换excel“相对日期”数字,即从设定日期计算的5位数字。

代码

for ($i = 0; $i -lt 6; $i++)
  {
  for ($i2 = 0;$i2 -lt 10; $i2++)
    {

    $ExcelDate = Import-Excel -Path $path -StartColumn 2 -EndColumn 2 -StartRow 7 -EndRow 20 
    -WorksheetName $WeekDays[$i]

        [DateTime]::FromOADate($ExcelDate[$i2])
     }   
   }

错误

Cannot convert argument "d",with value: "@{Date Del.=44293}",for 
"FromOADate" to type "System.Double": "Cannot convert the "@{Date Del.=44293}" 
value of type "System.Management.Automation.PSCustomObject" to type 
"System.Double"."
At H:\My Files\Jobs\Projects\In Progress\Killsheet Data Import\Importing data 
test v1.ps1:75 char:9
+         [DateTime]::FromOADate($ExcelDate[$i2])
+         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [],MethodException
    + FullyQualifiedErrorId : MethodArgumentConversionInvalidCastArgument

我需要帮助将@{date Del.=44293} 更改为“44293”的“字符串值”

解决方法

Import-Excel cmdlet 返回 PSCustomObject 类型的数组。单元格值存储为对象的属性,并且属性的名称设置为列的标题名称。因此,要访问该值,您需要编写 $ExcelDate[$i2].NameOfColumn

您应该注意到,Import-Excel 通常会设法为您将日期列转换为日期时间,因此您不需要使用 FromOADate 将其转换。

如果您不确定 Powershell 对象上的哪些属性可用,您可以使用 cmdlet Get-Member 进行检查。例如 $ExcelDate[$i2] | Get-Member 为我输出:

   TypeName: System.Management.Automation.PSCustomObject

Name                MemberType   Definition
----                ----------   ----------
Equals              Method       bool Equals(System.Object obj)
GetHashCode         Method       int GetHashCode()
GetType             Method       type GetType()
ToString            Method       string ToString()
MyExampleDateColumn NoteProperty datetime MyExampleDateColumn=2021-04-03 00:00:00