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.
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.
Olaf
August 30, 2018, 12:55am
3
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
Thanks very much Mr KVPrasoon, I had just amended my question - to a slightly different one, since I already found my mistake.
Many thanks Mr Olaf Soyk, much appreciated.
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'}
Sincerest thanks Mr Kvprasoon, this is very informative and useful.