Author Posts

August 30, 2018 at 4:47 am

I have a CSV file as follows:

"Title","Date","Comments"
"aaa","1/23/2016","action"
"bbb","8/31/2017","drama"
"ccc","12/4/2017","western"
"ddd","7/11/2018","thriller"

I have the following PS script:

$data = Import-csv .\Input.csv

$data | Select-object -property * |
    Foreach-object -process {
    @{ Newdate = ($_.Date -as [Datetime]).AddYears(2).ToString()); } |
Out-gridview

This works fine, but:

Q1 – how can I format the ToString() result to show only Date without the trailing TIME?

Q2 – is it possible to add a new property (towards the ultimate output file, not shown in the sample code) without an extra pipe to Add-Member?

Would be grateful for any tips or hints.

August 30, 2018 at 6:02 am

ForEach-Object is not required here, you can do it via calculated properties.

$data | Select-object -property Title,@{E={($_.Date -as [Datetime]).AddYears(2).ToString()};L='Date'},comments

Below is a good article by Adam on this.
https://mcpmag.com/articles/2017/01/19/using-powershell-calculated-properties.aspx

August 30, 2018 at 6:25 am

For me it works like this:

$Source = @'
"Title","Date","Comments"
"aaa","1/23/2016","action"
"bbb","8/31/2017","drama"
"ccc","12/4/2017","western"
"ddd","7/11/2018","thriller"
'@

$Data = ConvertFrom-Csv -Delimiter ',' -InputObject $Source

$data | 
    Foreach-object -process {
        [PSCustomObject]@{
            Title = $_.Title
            Date = (Get-Date -Year ($_.Date -split '/')[2] -Month ($_.Date -split '/')[0] -Day ($_.Date -split '/')[1]).Date.AddYears(2)
            Comments = $_.Comments
        } 
    }|
    Out-gridview

August 30, 2018 at 9:06 am

Thanks very much Mr KVPrasoon, I had just amended my question – to a slightly different one, since I already found my mistake.

August 30, 2018 at 1:31 pm

Many thanks Mr Olaf Soyk, much appreciated.

 

August 30, 2018 at 1:59 pm

Q1 – how can I format the ToString() result to show only Date without the trailing TIME?
Yes – you can use the ToShortDateString() method.

$data | Select-object -property Title,@{E={($_.Date -as [Datetime]).AddYears(2).ToShortDateString()};L='Date'},comments

Q2 – is it possible to add a new property (towards the ultimate output file, not shown in the sample code) without an extra pipe to Add-Member?
Yes, same calculated properties will do that.

$data | Select-object -property Title,@{E={($_.Date -as [Datetime]).AddYears(2).ToShortDateString()};L='Date'},comments,@{E={$_.Title + $_.Comments};L='NewItem'}

August 30, 2018 at 4:25 pm

Sincerest thanks Mr Kvprasoon, this is very informative and useful.