Home > Enterprise >  collect a value per console and multiply powershell
collect a value per console and multiply powershell

Time:10-01

I am trying to collect a value per console, in this case an ip address, and that the suffix of this is self-incrementally and multiplied by line up to 254. I tried with for, but this create each file text. thats my code.

$ipaddress=$args[0]
New-Item .\direcciones.txt -Force 
$filetext= New-Item .\direcciones.txt -Force 
for ($i=1, $i -le 254;)
{ Add-Content -Path $filetext -Value $ipaddress.$i }

i expect something like the filetext:

192.168.1.1
192.168.1.2
192.168.1.3
...
192.168.1.254

the autoincrement value that i want is the last octet and the 3 first is the $arg

CodePudding user response:

The key is to enclose $ipaddress.$i in "..."; additionally, you can streamline your code:

1..254 | ForEach-Object { "$ipaddress.$_" } | Set-Content $filetext

Or, more efficiently, but more obscurely:

1..254 -replace '^', "$ipaddress." | Set-Content $filetext

As for what you tried:

  • (This may just be a posting artifact) for ($i=1, $i -le 254;) creates an infinite loop, because you're missing ; $i for incrementing the iterator variable $i.

  • Even in argument-parsing mode, $ipaddress.$i - in the absence of enclosure in "..." - is interpreted as an expression, meaning that $i is interpreted as the name of a property to access on $ipaddress, which therefore results in $null, so that no data is written to the output file.

  • Only inside an expandable (double-quoted) string ("...") - i.e. "$ipaddress.$i" in this case - are $ipaddress and $i expanded individually.

  • Related