我正在设置一个脚本来自动化一些工作,并且遇到了一些麻烦。我尝试了一些在网上找不到的建议。
我的目标是在每一行中循环遍历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
答案 0 :(得分: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'}
}
答案 1 :(得分:0)
内部循环是不必要的,只需引用管道中当前项目的description
属性($_
):
Import-Csv $path | Foreach-Object {
switch ($_.description) {
2019 {
do something
}
2020 {
do something
}
2021 {
do something
}
2022 {
do something
}
}
}
答案 2 :(得分:0)
感谢大家的帮助!最后,我将我发布的内容和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"}
}
}