Welcome › Forums › General PowerShell Q&A › Replace last octet of IP addresses?
- This topic has 4 replies, 3 voices, and was last updated 3 weeks ago by
Participant.
-
AuthorPosts
-
-
December 30, 2020 at 8:49 am #283240
I am trying to get a list of IP addresses of the computer I am connected onto.
I have achieved this via:
$IPV4Addresses = Get-NetIPAddress -AddressFamily ‘IPv4’ | Select-Object -ExpandProperty ‘IPAddress’
This outputs as a list of 8 IP addresses. I’m wondering how I can replace the last octet on each IP address so they become xxx.xxx.xx.*
as a bonus I would also like to separate the final output by ;
Is this easy to achieve?
-
This topic was modified 3 weeks ago by
StockMinute31.
-
This topic was modified 3 weeks ago by
-
December 30, 2020 at 9:38 am #283246
since the output is a collection, a simple way would be to iterate through each of them and do split and join.
PowerShell123456$IPV4Addresses | ForEach-Object -Process {$SplitItem = $_.ToString() -split '\.'$SplitItem[3] = $NewLastOctet$NewIP = $SplitItem -Join '.'$NewIP}PS: Untested code
-
December 30, 2020 at 9:42 am #283252
Hi,
Thanks for this the output came out like this:
How can I now format that to separate by ; ?
-
This reply was modified 3 weeks ago by
StockMinute31.
-
This reply was modified 3 weeks ago by
-
December 30, 2020 at 11:15 am #283288
When working with IPs like that, I usually just use a ‘\d+$’ to replace the last octet.
For your desired output:
PowerShell1($IPV4Addresses | foreach {$_ -replace '\d+$','*'}) -join ';'-
December 30, 2020 at 12:18 pm #283303
That works great! thank you for this! 🙂
-
-
-
AuthorPosts
- You must be logged in to reply to this topic.