Powershell,循环遍历 CSV 并使用 Switch

Powershell, Loop through CSV and use Switch

我正在设置一个脚本来自动执行某些工作,但遇到了一些问题。我尝试了一些在网上找到的建议,但没有成功。

我的目标是遍历 CSV 文件,在每一行检查特定单元格的内容,然后 运行 基于该值的命令以及该行中的所有数据。

这是我现在拥有的。它不起作用,老实说,我不确定我是否有正确的语法来逐步浏览每一行,或者开关是否设置为读取标题 "Description" 并将其与下面的案例进行比较。

Import-Csv $path | Foreach-Object {

foreach ($property in $_.PSObject.Properties){
    switch ($property.description) {
        2019 {
            do something
        }
        2020 {
            do something
        }
        2021 {
            do something
        }
        2022 {
            do something
        }
    }
}
}

CSV 样本

firstname,lastname,name,samaccountname,password,email,description,CAMPUS_ID
1test,1senior,1test 1senior,01testsenior,test1234,01testsenior@website.com,2019,1
1test,1junior,1test 1junior,01testjunior,test1234,01testjunior@website.com,2020,1
1test,1sophomore,1test 1sophomore,01testsophomore,test1234,01testsophomore@website.com,2021,1
1test,1freshman,1test 1freshman,01testfreshman,test1234,01testfreshman@website.com,2022,1

试试这个 -

$obj = Import-Csv $path
switch($obj.PSObject.Properties.Value.Description)
{
    '2019' {'do 2019 thing'}
    '2020' {'do 2020 thing'}
    '2021' {'do 2021 thing'}
    '2021' {'do 2022 thing'}
    default {'do default thing'}
}

内部循环是不必要的,只需引用管道中当前项目的description 属性 ($_):

Import-Csv $path | Foreach-Object {
    switch ($_.description) {
        2019 {
            do something
        }
        2020 {
            do something
        }
        2021 {
            do something
        }
        2022 {
            do something
        }
    }
}

感谢大家的帮助!我最终将我发布的内容和 Mathias 修复的内容以及 Vivek 发布的内容结合起来。通过一些额外的修改将行存储到变量中,因为它们不会传递给开关。

Import-Csv 'PATH' | Foreach-Object {

$FirstName = $_.firstname
$LastName = $_.lastname
$Email = $_.email
$Password = $_.password
$Description = $_.description
$Campus = $_.CAMPUS_ID

    switch ($_.description) {
        '2019' {Do something with variables}
        '2020' {Do something with variables}
        '2021' {Do something with variables}
        '2022' {Do something with variables}
        default {echo "Default"}
    }
}