0

I have a list of IPs that is stored in .txt file at C:\IPs.txt

10.0.0.0
100.0.0.0

And a PowerShell script that executes commands for each entry in that file.

Get-Content C:\IPs.txt |ForEach-Object { Write-Host 1 - $_ }

So that command returns

1 - 10.0.0.0
1 - 100.0.0.0

How can I add +1 to a digit, so that PowerShell command would return:

1 - 10.0.0.0
2 - 100.0.0.0
WinBoss
  • 879
  • 1
  • 17
  • 40
  • As an aside: [`Write-Host` is typically the wrong tool to use](http://www.jsnover.com/blog/2013/12/07/write-host-considered-harmful/), unless the intent is to write _to the display only_, bypassing the success output stream and with it the ability to send output to other commands, capture it in a variable, redirect it to a file. To output a value, use it _by itself_; e.g., `$value` instead of `Write-Host $value` (or use `Write-Output $value`, though that is rarely needed). See also: the bottom section of https://stackoverflow.com/a/50416448/45375 – mklement0 Mar 14 '20 at 03:53

3 Answers3

1

It's not a one liner, but you could do something like this:

$IPs = Get-Content C:\temp\text.txt #Note this was my test file
$i = 1

foreach($IP in $IPs)
{
    Write-Host "$i - $IP"
    $i ++
}

Edit: As a one liner:

Get-Content C:\temp\text.txt | ForEach-Object {$l++; Write-Host "$l - $_" }
Thom A
  • 88,727
  • 11
  • 45
  • 75
1

This might give you the desired output.

Get-Content C:\IPs.txt | ForEach-Object { Write-Host "$($_.ReadCount) - $_" }
notjustme
  • 2,376
  • 2
  • 20
  • 27
1

Something with the -f operator:

get-content ips.txt | foreach { $i = 1 } { "{0} - {1}" -f $i++, $_ } 

1 - 10.0.0.0
2 - 100.0.0.0

Or this, I needed extra parentheses for the $i++ to output something:

get-content ips.txt | foreach { $i = 1 } { "$(($i++)) - $_" } 

1 - 10.0.0.0
2 - 100.0.0.0

Or something more powershelly, output an object:

$i=1; get-content ips.txt | select @{n='index';e={($global:i++)}},
  @{n='address'; e={$_}}

index address
----- -------
    1 10.0.0.0
    2 100.0.0.0
js2010
  • 23,033
  • 6
  • 64
  • 66