Reputation: 923
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
Upvotes: 0
Views: 2262
Reputation: 27556
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
Upvotes: 1
Reputation: 2494
This might give you the desired output.
Get-Content C:\IPs.txt | ForEach-Object { Write-Host "$($_.ReadCount) - $_" }
Upvotes: 1
Reputation: 95950
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 - $_" }
Upvotes: 1