【问题标题】:Powershell, Loop through CSV and use SwitchPowershell,循环通过 CSV 并使用 Switch
【发布时间】:2018-08-27 14:40:37
【问题描述】:

我正在设置一个脚本来自动化一些工作,但遇到了一些麻烦。我尝试了一些在网上找到的建议,但没有运气。

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

这就是我现在所拥有的。它不起作用,老实说,我不确定我是否有正确的语法来遍历每一行,或者开关是否设置为读取标题“描述”并将其与下面的案例进行比较。

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

【问题讨论】:

  • 你能提供一些你的CSV吗?
  • 如果您添加到您的初始问题,它可能会正确格式化
  • 用 CSV 示例更新了原始帖子。

标签: powershell import-csv


【解决方案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'}
}

【讨论】:

  • 我测试了这个,它似乎工作。但是,我无法让它与我正在使用的命令一起使用。像这样 "$obj.PSObject.Properties.Value.email" 引用行的数据是否有意义?这将引用当前正在使用的行的“电子邮件”列?
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

    感谢大家的帮助!我最终结合了我发布的内容、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"}
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-10
      • 1970-01-01
      • 1970-01-01
      • 2013-12-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多