Reputation: 13
I'm setting up a script to automate some work and am having some trouble. I've tried some suggestions found online with no luck.
My goal is to loop through a CSV file, at each row, checking a specific cell for it's content, and then running a command based on that value with all the data in that row.
Here's what I have right now. It doesn't work, and I'm honestly not sure if I even have the syntax correct for stepping through each row, or if the switch is even setup to read the heading "Description" and compare it with the cases below.
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
}
}
}
}
Sample of CSV
firstname,lastname,name,samaccountname,password,email,description,CAMPUS_ID
1test,1senior,1test 1senior,01testsenior,test1234,[email protected],2019,1
1test,1junior,1test 1junior,01testjunior,test1234,[email protected],2020,1
1test,1sophomore,1test 1sophomore,01testsophomore,test1234,[email protected],2021,1
1test,1freshman,1test 1freshman,01testfreshman,test1234,[email protected],2022,1
Upvotes: 1
Views: 1405
Reputation: 13
Thanks everyone for helping! I ended up combining both what I posted, and Mathias fixed, and what Vivek posted. With some additional modification to store the row into variables, because they don't pass to switches.
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"}
}
}
Upvotes: 0
Reputation: 174815
The inner loop is unnecessary, just reference the description
property of the current item in the pipeline ($_
):
Import-Csv $path | Foreach-Object {
switch ($_.description) {
2019 {
do something
}
2020 {
do something
}
2021 {
do something
}
2022 {
do something
}
}
}
Upvotes: 0
Reputation: 3350
Try this -
$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'}
}
Upvotes: 1