0

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
},

2 Answers 2

1

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

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

With this:

$stringToEdit -replace "replace","$entry"
Sign up to request clarification or add additional context in comments.

Comments

0

replace $ip with $entry

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

2 Comments

Can you expand a bit on why your solution solves the problem?
I wanted this to use this to as a piece of code for a tool to add new entries in to a firewall. The code takes the string and the only thing that changed is the part i put replace in. I then to looped through each ip in the list and replaced the 'replace' text with the ip and then I added it to the array so in the end the output is showing what I want and I can just use this code in correlation with other code to add new entries on the fly or with a csv.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.