Search code examples
powershellcsvpowershell-3.0

Import/Export .csv file


I have testDates.csv with 100 dates

date
1/10/17
6/10/18
9/10/42
...

I made a script that makes sample passwords based off these dates:

$file = Import-Csv -Path U:\Desktop\testDates.csv

foreach ($line in $file) {
    $fullDate = $line.date
    $year = Get-Date $fullDate -Format "yy"
    $currentDate = Get-Date $fullDate -Format "MM-dd"

    # Determining season
    if ($currentDate -ge (Get-Date 01-01) -and $currentDate -lt (Get-Date 03-01)) {
        $season = "Winter"
    } elseif ($currentDate -ge (Get-Date 03-01) -and $currentDate -le (Get-Date 05-31)) {
        $season = "Spring"
    } elseif ($currentDate -ge (Get-Date 06-01) -and $currentDate -le (Get-Date 08-31)) {
        $season = "Summer"
    } elseif ($currentDate -ge (Get-Date 09-01) -and $currentDate -le (Get-Date 11-30)) {
        $season = "Fall"
    } elseif ($currentDate -ge (Get-Date 12-01) -and $currentDate -le (Get-Date 12-31)) {
        $season = "Winter"
    } else {
        $season = "ClearyAnIntern"
    }

    # Creating password
    $SamplePassword = $season + $year
}

I want to export the created password back to the original .csv in a new column. So have a column "passwords" next to "dates" to see if my script works correctly. Example:

date    password
1/10/17 Winter17
6/10/18 Summer18
9/10/42 Fall42
...     ...

I know it involves Export-Csv but I don't know how to pipe it especially for each line. I've been looking at tons of different threads and the MS help center for how to use the different parameters such as -Append and so forth but everything I've seen and tried isn't exactly what I'm dealing with and to infer from those examples is outside the scope of my remedial knowledge at the moment. I'm beginning to believe this may involve nested foreach loops.


Solution

  • Import-Csv C:\path\input.csv | ForEach-Object {
       $seasons = [Char[]]'wwsssmmmfffw' # seasons map
    }{ # walk around CSV lines
       [PSCustomObject]@{
          Date = $_.date # first and second columns of future CSV
          Password = "$(switch ($seasons[([DateTime]$_.date).Month - 1]) {
             'w' {'Winter'} 's' {'Spring'} 'm' {'Summer'} 'f' {'Fall'}
          })$(Get-Date $_.date -Format yy)"
       }
    } | Export-Csv C:\path\out.csv # export result