hello,
I’m looking for some guidance on how to modify an array initially loaded from Excel. The modifications are based on conditions, ie, so for a real simple example, if $item.Unit contains a dash, then change the value of B, etc.
Here’s a simplified version of the code:
$dataArray = Import-Excel -Path $excelInPath -Startrow 2 -StartColumn 1 -EndColumn 20
foreach ($item in $dataArray) {
$msg = new-object -Typename psobject -property @{
A = $item.Unit;
B = $item.Country;
C = $item.Dept;
D = $item.Level;
}
if($msg.Unit.contains(“-”)) {
$msg.Country = 200;
}
I’m getting a runtime error if I leave the if() statement, but do need a way to modify the array. Any input is greatly appreciated.
Many thanks.
Lacour
Hello, welcome to the forum. When posting code or errors, please use the preformatted option (looks like this </> and may be hidden under the settings gear.)
I see three issues with your code.
It appears you’ve copied this code from a website that didn’t use a good formatting for code. The double quotes are “fancy”. Just type those out manually to replace them. “-” bad quotes "-" good quotes
You are missing a curly brace. This is much easier to spot when you properly indent the code. I didn’t notice this issue until I went to fix it and it became obvious.
You are referencing the wrong property name. In your $msg object, you have 4 properties. A, B, C, and D.
$dataArray = Import-Excel -Path $excelInPath -Startrow 2 -StartColumn 1 -EndColumn 20
foreach ($item in $dataArray) {
$msg = new-object -Typename psobject -property @{
A = $item.Unit
B = $item.Country
C = $item.Dept
D = $item.Level
}
if($msg.A.contains("-")) {
$msg.B = 200
}
}
As an aside, the semicolon’s are not required here.