user9924807
user9924807

Reputation: 787

Insert quotes at start and end of string array

I have an array of IP addresses, sample array below:

$arr = "22.22.22.22", "33.33.33.33", "44.44.44.44"

I am trying to insert quotes " at the start & end of each IP and convert the array to a string value. I have tried:

$arr | ForEach-Object { $newArr += $_.Insert(0,'" ') }

Output:

$newArr
" 22.22.22.22" 33.33.33.33" 44.44.44.44

Desired string output:

"22.22.22.22" "33.33.33.33" "44.44.44.44"

Is this possible using powershell?

Upvotes: 1

Views: 854

Answers (2)

Theo
Theo

Reputation: 61028

Or make use of the -f Format operator.

Something like

($arr | ForEach-Object { '"{0}"' -f $_ }) -join ' '

or shorter:

'"{0}"' -f ($arr -join '" "')

Upvotes: 2

Paolo
Paolo

Reputation: 26014

Here's one idea. First, convert the array to a string with the " " separator, then prepend and append the " character.

$newStr = '"' + [system.String]::Join('" "',$arr) + '"'
# "22.22.22.22" "33.33.33.33" "44.44.44.44"

Upvotes: 2

Related Questions