简体   繁体   English

Powershell import-csv 更改日期格式

[英]Powershell import-csv to change date format

I'm trying to convert a date through Powershell import-csv and need some help please: I've simplified the content of the csv file to give an example which appears as:我正在尝试通过 Powershell import-csv 转换日期,需要一些帮助:我已经简化了 csv 文件的内容,以给出一个示例,如下所示:

"ServerName","InstallDate"
"SRV1","20220506"

Then I use Powershell command:然后我使用 Powershell 命令:

Import-Csv 'c:\results\data.csv' | select servername, installdate

The import date is currently in the form of year/month/date and I need it converting to month/date/year eg 05062022 based on sample data above.导入日期目前采用year/month/date的形式,我需要根据上面的示例数据将其转换为month/date/year例如05062022

I've experimented with [datetime]::ParseExtact but am getting nowhere with it, can anyone help with this?我已经尝试过[datetime]::ParseExtact但没有任何进展,有人可以帮忙吗? Thanks谢谢

Assuming all values in the InstallDate column are populated and follow the same format then this should work:假设InstallDate列中的所有值都已填充并遵循相同的格式,那么这应该可以工作:

Import-Csv path\to\csv | ForEach-Object {
    $_.InstallDate = [datetime]::ParseExact($_.InstallDate, 'yyyyMMdd', [cultureinfo]::InvariantCulture).ToString('MMddyyyy')
    $_
} | Select-Object ServerName, InstallDate

Here is an example for testing using hardcoded CSV in a string:以下是在字符串中使用硬编码 CSV 进行测试的示例:

@'
"ServerName","InstallDate"
"SRV1","20220506"
"SRV2","20220507"
'@ | ConvertFrom-Csv | ForEach-Object {
    $_.InstallDate = [datetime]::ParseExact($_.InstallDate, 'yyyyMMdd', [cultureinfo]::InvariantCulture).ToString('MMddyyyy')
    $_
}

In case there could be empty values in the column you can add a simple condition to check if String.IsNullOrWhiteSpace , and if it is, ignore that line:如果列中可能有空值,您可以添加一个简单的条件来检查String.IsNullOrWhiteSpace是否存在,如果是,则忽略该行:

Import-Csv path\to\csv | ForEach-Object {
    # if the value on `InstallDate` property is empty or white space
    if([string]::IsNullOrWhiteSpace($_.InstallDate)) {
        # return this object as-is without any modifications,
        # and go to the next item
        return $_
    }

    # here we assume the property is populated, so we can update it
    $_.InstallDate = [datetime]::ParseExact($_.InstallDate, 'yyyyMMdd', [cultureinfo]::InvariantCulture).ToString('MMddyyyy')
    $_
} | Select-Object ServerName, InstallDate

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM