Sanwil9
Sanwil9

Reputation: 307

String manipulation in foreach powershell

The output of this code is confusing me. I'm almost positive it's my logic on this.

I want to loop through the $stringToEdit Variable and replace the 'replace' text with an element of the $ip collection.

The output does give three blocks as expected but the 'replace' has ALL three of the elements. I thought it should only be each element. What am I doing wrong?

Code is below

$ip = @('172.168.1.1','172.168.3.1','172.168.2.1')
$stringToEdit = @"
    {
        address : replace
        interface : 'nic0'
        policy : 'allow'
        prefix : 32
    },
"@
$array = @()
$array = ForEach($entry in $ip) {
    $stringToEdit -replace "replace","$ip"
}
$array

Output is

{
    address : 172.168.1.1 172.168.3.1 172.168.2.1
    interface : 'nic0'
    policy : 'allow'
    prefix : 32
},
{
    address : 172.168.1.1 172.168.3.1 172.168.2.1
    interface : 'nic0'
    policy : 'allow'
    prefix : 32
},
{
    address : 172.168.1.1 172.168.3.1 172.168.2.1
    interface : 'nic0'
    policy : 'allow'
    prefix : 32
},

Upvotes: 0

Views: 570

Answers (2)

Dabang
Dabang

Reputation: 41

replace $ip with $entry

$stringToEdit -replace "replace","$entry"

Upvotes: 0

Jordan
Jordan

Reputation: 413

You use the wrong variable in your foreach block Replace this line:

$stringToEdit -replace "replace","$ip"

With this:

$stringToEdit -replace "replace","$entry"

Upvotes: 1

Related Questions