Import/Export.csv 文件

Import/Export .csv file

我 testDates.csv 有 100 个日期

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

我制作了一个脚本,根据这些日期制作示例密码:

$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
}

我想将创建的密码导出回新列中的原始 .csv。因此,在 "dates" 旁边有一列 "passwords" 以查看我的脚本是否正常工作。示例:

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

我知道它涉及 Export-Csv,但我不知道如何通过管道将其特别是每一行。我一直在查看大量不同的线程和 MS 帮助中心,了解如何使用 -Append 等不同的参数,但我所看到和尝试的一切并不完全是我正在处理的目前,从这些例子中进行推断超出了我的治疗知识范围。我开始相信这可能涉及嵌套 foreach 循环。

Export-Csv 需要一个对象列表作为输入,因此这是您首先需要创建的。

foreach ($line in $file) {
    ...
    [PSCustomObject]@{
        'date'     = $fullDate
        'password' = $SamplePassword
    }
}

接下来,foreach 循环无法写入管道,因此您需要在循环内追加到输出文件:

foreach ($line in $file) {
    ...
    [PSCustomObject]@{
        'date'     = $fullDate
        'password' = $SamplePassword
    } | Export-Csv 'output.csv' -NoType -Append
}

或者将输出收集到一个变量中然后导出:

$list = foreach ($line in $file) {
    ...
    [PSCustomObject]@{
        'date'     = $fullDate
        'password' = $SamplePassword
    }
}

$list | Export-Csv 'output.csv' -NoType

否则你需要用ForEach-Object循环替换foreach循环:

Import-Csv 'U:\Desktop\testDates.csv' | ForEach-Object {
    $fullDate = $_.date
    ...
    [PSCustomObject]@{
        'date'     = $fullDate
        'password' = $SamplePassword
    }
} | Export-Csv 'output.csv' -NoType

您可以使用 Calculated properties 结合 for 循环来执行此操作。同样的说明如下 -

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

#Declaring the variable to store passwords
$SamplePassword = @()

#loop
foreach ($line in $file)
{
    #Variable declarations
    $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
}

完成上述步骤后,您的 $SamplePassword 将包含所有密码。使用带有 for 循环的计算属性,如下所示 -

#Declaring a new variable to store the results
$NewCsv = @()
$Originalcsv = Import-Csv -path U:\Desktop\testDates.csv
for($i = 0; $i -lt $Originalcsv.Length; $i++)
{
    $NewCsv += $Originalcsv[$i] | Select-Object *, @{Name='Password';Expression={$SamplePassword[$i]}}
}

$NewCsv | Export-Csv U:\Desktop\NewtestDatesWithPasswords.csv -NoTypeInformation

我猜你的 csv 文件中的日期格式是 M/d/yy ? 从 csv 导入变量类型总是字符串,因为我自己的语言环境偏离我必须定义不同的文化来转换。

使用我的 function Get-Season 来自你的其他问题的修改版本。

## Q:\Test18\SO_50976425.ps1
## define function first
Function Get-Season([datetime]$Date){
    If (!$Date) {$Date = Get-Date} #If date was not provided, assume today.
    # The dates are obviously not exactly accurate and are best guesses
    $Spring = Get-Date -Day 20 -Month 03 -Year $Date.Year
    $Summer = Get-Date -Day 21 -Month 06 -Year $Date.Year
    $Autumn = Get-Date -Day 22 -Month 09 -Year $Date.Year
    $Winter = Get-Date -Day 21 -Month 12 -Year $Date.Year
    $Season = switch($Date) {
        {($_ -lt $Spring)}  {"Winter";Break}
        {($_ -lt $Summer)}  {"Spring";Break}
        {($_ -lt $Autumn)}  {"Summer";Break}
        {($_ -lt $Winter)}  {"Autumn";Break}
        {($_ -ge $Winter)}  {"Winter"}
    }
    "{0}{1}" -f $Season,$Date.ToString('yy')
}

#Importing csv dates file
$file = Import-Csv -Path '.\testDates.csv'

# get CultureInfo
$CIUS = New-Object System.Globalization.CultureInfo("en-US")

# process $file and create a new PSCustomObject
$DatePassw = foreach ($line in $file){
    $fullDate = [datetime]::ParseExact($line.date,"M/d/yy",$CIUS)
    [PsCustomObject]@{
        date     = $line.date
        password = (Get-Season $fulldate)
    }
}
$DatePassw | ft
$DatePassw | Export-Csv '.\testdatepassw.csv' -NoTypeInformation

示例输出:

> .\SO_50976425.ps1

date    password
----    --------
1/10/17 Winter17
6/10/18 Spring18
9/10/42 Summer42

> gc .\testdatepassw.csv
"date","password"
"1/10/17","Winter17"
"6/10/18","Spring18"
"9/10/42","Summer42"
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