Joe
Joe

Reputation: 13

Passing custom variable properties into foreach statement

I am trying to pass multiple variables into one foreach statement using custom properties but the custom property is not being passed inside the foreach statement

$input = "one two three"

$tests = "true false true"

Add-Member -InputObject $tests -MemberType NoteProperty -Name "Name" -Value $input



foreach ($test in $tests) {

    Write-Host $test.Name
    Write-Host $test

}

expected output:

one
true
two
false
three
true

Any help would be greatly appreciated.

Upvotes: 1

Views: 142

Answers (2)

boxdog
boxdog

Reputation: 8432

As mentioned in Randips's answer, you have some issues with the setup/use of your 'array', which he addresses.

In terms of adding custom properties, I think you are running into the immutability of strings in .NET. Once created they can't be changed, so you aren't able to add new members. Other types work fine. For example, you can do this with a process object:

$propValue= "one two three"

$proc= (Get-Process)[33]

Add-Member -InputObject $proc -MemberType NoteProperty -Name "MyProperty" -Value $propValue

Write-Host $proc.MyProperty
Write-Host $proc

Which gives output like this:

one two three
System.Diagnostics.Process (devenv)

Upvotes: 1

Ranadip Dutta
Ranadip Dutta

Reputation: 9133

So there are lot of things to address. First of all the foreach loop works on array. So your variable declaration is wrong. It has to be comma separated or it has to be in an array format.

like this

$input = "one", "two", "three"

$tests = "true", "false", "true"

OR

$input = @("one", "two", "three")

$tests = @("true", "false", "true")

Foreach loop cannot operation on multiple arrays at a while ; in your case you should be using For loop like

$input = "one", "two", "three"

$tests = "true", "false", "true"


foreach ($test in $tests) ## For looping through single array
{
    Write-Host $test
}

If($input.Length -match $tests.Length)  ## Forlooping through multiple arrays
{
    For($i=0;$i -lt $input.Length; $i++) 
    {
        "$($input[$i]) :: $($tests[$i])"
    }
}

and for your Expected Format, it should be:

$input = "one", "two", "three"

$tests = @("true", "false", "true")

If($input.Length -match $tests.Length) 
{
    For($i=0;$i -lt $input.Length; $i++) 
    {
        "$($input[$i])"
        "$($tests[$i])"
    }
}

OUTPUT:

one 
true 
two 
false 
three 
true

PS: Now you can easily incorporate the Add-Member -InputObject $tests -MemberType NoteProperty -Name "Name" -Value $input based on this logic.

Hope it helps.

Upvotes: 3

Related Questions