简体   繁体   中英

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

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

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

With this:

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

用$ entry代替$ ip

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM