0

I have a output like below from a command

IpPrefix
--------
15.181.232.0/21
142.4.160.136/29
3.2.0.0/24
161.188.154.0/23

Using above output, need write a command in powershell to get format like :

15.181.232.0/21,142.4.160.136/29,3.2.0.0/24,161.188.154.0/23

Basically combine multiple lines to one line with comma separated. Please help.

1
  • 3
    (<existing command/pipeline> |ForEach-Object IpPrefix) -join ',' Commented Jul 14, 2022 at 12:50

1 Answer 1

2

Welcome to PowerShell! The results of commands are objects. This object you have made has at least 1 property called IpPrefix. If your object is stored in a variable $object, then you can reference the property like this:

$object = (some-command -param something)
$object.IpPrefix

Once you're got the items in just that one column, without the column header, you now have an array of strings. They're still objects, but they are string objects.

The -join operator works against arrays.

$object = (some-command -param something)
$object.IpPrefix -join ','

This will give you what you want in the simplest way possible.

Let's say maybe you don't want to store your data in a variable (aka in Memory). You might have a pipeline or some other situation where storing the data slows you down. You would do that like this:

(some-command -param something).IpPrefix -join ','

Same idea, different syntax. Hope this helps you understand the shell better!

Sign up to request clarification or add additional context in comments.

Comments

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.