Powershell从Excel列导入的日期和时间使用错误的格式导入



我正在使用导入Excel模块将Excel文档导入powershell脚本。导入效果很好,但带有日期的列的格式真的很奇怪。Excel工作表中的日期和时间格式如下:yyyy-mm-dd hh:mm(2020-09-01 04:03(,但导入的数据格式如下:439651672916667。

我尝试将[DateTime]添加到变量中,如下所示:"Senast ansluten" = [DateTime]$ExcelLok.'Senast ansluten'但后来我就犯了错误Cannot convert value "44075.3451851852" to type "System.DateTime". Error: "String was not recognized as a valid DateTime."

如何指定格式以便正确读取?

$ImportExcel = Import-Excel -Path 'C:TempPowershell scriptsTestPingFastaIPFasta IP-nummer.xlsm' -WorksheetName ADM_UTB
ForEach ($ExcelLok in $ImportExcel){
[PSCustomObject]@{
"IP address" = $ExcelLok.IP
"Lokation" = $ExcelLok.Lok
"Ping status" = $ExcelLok.'Ping status'
"Senast ansluten" = [DateTime]$ExcelLok.'Senast ansluten'
} | Format-Table -Property `
@{Name='Lokation';Expression={ $ExcelLok.Lok };align='left';width=15},
@{Name='IP address';Expression={ $ExcelLok.IP };align='left';width=15},
@{Name='Ping status';Expression={ $ExcelLok.'Ping status' };align='left';width=20},
@{Name='Senast ansluten';Expression={ $ExcelLok.'Senast ansluten' }} 

}

试试这个:$ImportExcel = Import-Excel -Path 'C:TempPowershell scriptsTestPingFastaIPFasta IP-nummer.xlsm' -WorksheetName ADM_UTB -AsDate 'DateColumn'

多亏了mclayton,解决方案变成了这样:

$ImportExcel = Import-Excel -Path 'C:TempPowershell scriptsTestPingFastaIPFasta IP-nummer.xlsm' -WorksheetName ADM_UTB
ForEach ($ExcelLok in $ImportExcel){
[PSCustomObject]@{
"IP address" = $ExcelLok.IP
"Lokation" = $ExcelLok.Lok
"Ping status" = $ExcelLok.'Ping status'
"Senast ansluten" = [DateTime]::FromOADate($ExcelLok.'Senast ansluten')
} | Format-Table -Property `
@{Name='Lokation';Expression={ $ExcelLok.Lok };align='left';width=15},
@{Name='IP address';Expression={ $ExcelLok.IP };align='left';width=15},
@{Name='Ping status';Expression={ $ExcelLok.'Ping status' };align='left';width=20},
@{Name='Senast ansluten';Expression={ [DateTime]::FromOADate($ExcelLok.'Senast ansluten') }} 

}

最新更新