0

I have a piece of code whereby someone enters a comma seperated string as a parameter like so:

[string[]] $ipAddressList = "123.113.331.31, 33.33.23.41,22.323.233.14"

        foreach($ipAddress in $ipAddressList.Split(",").Trim())
        {   
            Write-Host "1|${ipAddress}|" -NoNewline
        }

This is displaying data the exact way I want in this format: 1|123.113.331.31|1|33.33.23.41|1|22.323.233.14| (this is used for an internal program)

How do I assign this value returned to me into a variable as I need to insert it into a configuration file?

Thanks Rob

Robert
  • 75
  • 1
  • 7
  • 2
    DO NOT use `Write-Host` for anything other than what it is designed for - display on-screen. [*grin*] yes, there are workarounds, but they are graceless AND unneeded. assign it to a $Var and send that to wherever you want it to go. ///// also, take a look at the `-f` string format operator OR using `$Collection -join '|'`. – Lee_Dailey Nov 18 '20 at 20:16

2 Answers2

3

Write-Host means "output to the screen". A good rule of thumb is that you almost never want to use Write-Host because it's output cannot be assigned to anything. It really means output to the screen. The return value of the command is, as you have probably discovered, no output.

You can solve your problem like so:

On PowerShell 7:

$MyInput = "123.113.331.31, 33.33.23.41,22.323.233.14"

$MyOutput = $MyInput.Split(',').Trim() | ForEach-Object { "1|$_|" } | Join-String

On PowerShell 5 or earlier:

$MyInput = "123.113.331.31, 33.33.23.41,22.323.233.14"

$MyOutput = -join $($MyInput.Split(',').Trim() | ForEach-Object { "1|$_|" })
Bacon Bits
  • 30,782
  • 5
  • 59
  • 66
0

You could use the read-host command to ask the user for input.

$ipAddressList= Read-Host "Please enter the IP Address list"

More information from the Microsoft documentation,

https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/read-host?view=powershell-7.1

Shaqil Ismail
  • 1,794
  • 1
  • 4
  • 5