• 0

[Powershell] Generate Random IP's


Question

function RandomIPv4 {
    [IPAddress]::Parse([String] (Get-Random) )
}

I am trying to learn powershell at the moment, The reason isn't too important at this stage but anyone who is familiar with Powershell tell me if this will generate a random IP address and how could I use it in a function of sorts? 

Link to comment
https://www.neowin.net/forum/topic/1229005-powershell-generate-random-ips/
Share on other sites

7 answers to this question

Recommended Posts

  • 0

Yes, it does generate a random IP, although if that's the only data you want (and not the whole IP address object) you may want to narrow the return result a tad, that's up to you and your needs, just tossing that option if it comes up. Calling it is pretty easy, such as:

 

function RandomIPv4 {
return [IPAddress]::Parse([String] (Get-Random) ).IPAddressToString
}

Write-Output (RandomIPv4)
If you return the whole object, you get something like this, removing the actual return value:

 

Address : ########
AddressFamily : InterNetwork
ScopeId :
IsIPv6Multicast : False
IsIPv6LinkLocal : False
IsIPv6SiteLocal : False
IsIPv6Teredo : False
IsIPv4MappedToIPv6 : False
IPAddressToString : ###.###.###.###
And you could pick out the string version this way:

function RandomIPv4 {
return [IPAddress]::Parse([String] (Get-Random) )
}
Write-Output (RandomIPv4).IPAddressToString
Like I said, depends on what you're doing with it.
  • 0

Wow! Thanks thats great. I really want to get into Powershell so I am throwing some ideas round to learn bits and bobs. I want to say print them to an Excel Spreadsheet, Ping them, Check them for services write it to a spreadsheet etc.

  • 0
  On 09/09/2014 at 14:39, ChuckFinley said:

Wow! Thanks thats great. I really want to get into Powershell so I am throwing some ideas round to learn bits and bobs. I want to say print them to an Excel Spreadsheet, Ping them, Check them for services write it to a spreadsheet etc.

No problem -- PowerShell is absurdly good (my favorite shell by far) once you get the hang of it, crazy flexible.
  • 0

I might tap you for more information then :-p

 

So say for example I am going to write a program that would loop round, generate 50 random IP's ping them and output the results to a spreadsheet using 

 

http://technet.microsoft.com/en-us/library/ee176825.aspx

 

.....

  • 0

This is just off the top of my head, seems to work, you'll obviously want to edit it to suit your needs, change where it's being saved (got it going to your desktop at the moment), etc etc, but:

 

function RandomIPv4 {
    return [IPAddress]::Parse([String] (Get-Random) ).IPAddressToString
}

function RandomIPv4AddressList {
    $IPArray = @()
    for($Counter = 1 
        $Counter -le 50
        $Counter ++)
        {
            $IPObject = New-Object PSObject
            $IPObject | Add-Member -MemberType NoteProperty -Name "IP Address" -Value (RandomIPv4)
            $IPArray += $IPObject
        } 
        Return ($IPArray)
}

$OutputFileName = $Env:UserProfile + "\Desktop\IPAddressList.csv"
Write-Output(RandomIPV4AddressList) | Export-Csv $OutputFileName -NoTypeInformation  
The new function returns an array that Export-Csv can cleanly deal with and export.

For pinging you can use "Test-Connection", call that and add the result as another member in the IPArray object. Need to jet shortly for a client, if you still need help with it later I can expand on it this afternoon.

http://technet.microsoft.com/en-us/library/hh849808.aspx

  • 0
  On 09/09/2014 at 15:40, ChuckFinley said:

Wow thanks! What (if any) Powershell IDE do you recommend?

I don't do a ton of scripting myself so PowerShell ISE is plenty good enough for my needs. I do have a friend who is pretty fond of a program called "PowerShell Plus", never used it myself but looks interesting enough.
This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • Swatle AI — the smarter way to manage your teams, projects, and tasks now 75% off by Steven Parker Today's highlighted deal comes via our Apps + Software section of the Neowin Deals store, where you can save 75% off on Swatle All-in-One AI Assistant (Premium lifetime subscription). Stop over-hiring and overspending to meet your productivity goals. Swatle is all you need to achieve more with less. Swatle is an all-in-one AI solution designed to supercharge your productivity without over-hiring or overspending. Whether you're managing projects, automating repetitive tasks, or organizing your team's workflow, Swatle can help you achieve more with less. Powered by cutting-edge artificial intelligence, it adapts to your needs, streamlines operations, and eliminates inefficiencies so you can focus on what matters most—growing your business. With Swatle, working smarter isn’t just a goal—it’s your new reality. Let Swatle AI handle the necessary mundane tasks. SWATLE AI PROJECT ASSISTANT Step-by-Step Guidance: For every task you assign, either write step-by-step instructions yourself or let Swatle AI write on your behalf Skip the Standups: Ask Swatle AI about project progress and get instant, actionable updates—no daily meetings needed Accurate Time Estimates: Plan your day better by estimating the time required to complete your tasks Message Refinement: Send crystal clear messages; Swatle AI will rephrase your message & make it crisp and clear Project Quality Boost: Turn normal project descriptions into a crystal-clear description TEAM COLLABORATION MADE EASY Streamline Communication: Send & receive messages and updates within Swatle for real-time, tool-free collaboration Centralized Team Portfolios: Create dedicated portfolios to highlight your team's expertise & track their contributions effectively Conversational Task Creation: Instantly create tasks while having casual conversations with a single click. Make sure nothing falls through the crack Share Files & Feedback Directly: Eliminate scattered documents and email threads by sharing files and providing feedback directly in Swatle chat SWATLE TASKDESK Non-Technical Projects: Specifically designed for projects like marketing campaigns, content creation, and event planning Visualize Work Your Way: Manage tasks through Kanban boards, lists, Gantt charts, or Timelines—whatever fits your flow AI Task Assistant: Break down complex tasks into manageable subtasks quickly & easily Workload Tracking: View the workload of your team members & distribute tasks across the team to encourage a balanced workload. Proactive Notifications: Effortlessly keep your projects on track with timely, proactive notifications SWATLE DEVBOARD Technical Projects: Create unlimited sprints & backlogs for full control and visibility into every phase of your projects Burndown Chart: Provides a clear, real-time visual representation of your team's work remaining against the sprint timeline Set Goals, Create Sprints, Achieve More: Define your objectives and launch focused sprints that empower your team to concentrate on key tasks within short, impactful cycles Why choose Swatle? No Learning Curve: Swatle offers a remarkably easy-to-use interface. Empower your entire team to understand project progress without requiring technical expertise. Actionable Intelligence: Swatle turns raw project data into visualizations, like Assigned vs Completed charts, enabling focused analysis without manual effort. Proactively Mitigate Risks: Swatle visual dashboards make it easy to spot potential delays, bottlenecks, and resource imbalances, enabling you to take timely action and keep your projects on track. Ensure Resources Are Optimized: By visualizing workloads, you can strategically distribute tasks, promote a balanced environment, and prevent team burnout. Maintain Project Alignment & Stakeholder Confidence: Keep everyone from your internal team to clients and stakeholders on the same page with clear Gantt and Timeline views. Good to know Length of access: lifetime Redemption deadline: redeem your code within 30 days of purchase Access options: desktop or mobile Max number of device(s): unlimited Available to both NEW and Existing users Updates included This Swatle All-in-One AI Assistant (Premium lifetime subscription) normally costs $240, but this deal can be yours for just $59.99, that's a saving of $180. For full terms, specifications, and license info please click the link below. Get this lifetime Swatle Premium deal for just $59.99 (75% off) or learn more Although priced in U.S. dollars, this deal is available for digital purchase worldwide. We post these because we earn commission on each sale so as not to rely solely on advertising, which many of our readers block. It all helps toward paying staff reporters, servers and hosting costs. Other ways to support Neowin Whitelist Neowin by not blocking our ads Create a free member account to see fewer ads Make a donation to support our day to day running costs Subscribe to Neowin - for $14 a year, or $28 a year for an ad-free experience Disclosure: Neowin benefits from revenue of each sale made through our branded deals site powered by StackCommerce.
    • Meta is also trying to push that data scrapping copy protected work is "fair use" in the US to try and get out of a lawsuit. OpenAI is also trying to use that angle as well. This is after Meta they got caught downloading books from piracy book sites to feed their AI.
    • Stick to your weed and keep your medical "knowledge" to yourself.
    • Elder abuse lie? It's on the record. He couldn't stand prosecution for his mishandling of classified records because he was a doddering old fool literally puppeteered by his handlers and family. But you just want to steal content let's be honest here.
    • Not Netflix's fault and they had to switch to content creation. Content owners jacked up prices, won't allow them renew, and didn't give them the option to license new content.
  • Recent Achievements

    • Reacting Well
      sultangris earned a badge
      Reacting Well
    • First Post
      ClarkB earned a badge
      First Post
    • Week One Done
      Epaminombas earned a badge
      Week One Done
    • Week One Done
      Prestige Podiatry Care earned a badge
      Week One Done
    • Week One Done
      rollconults earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      144
    2. 2
      Xenon
      128
    3. 3
      ATLien_0
      124
    4. 4
      +Edouard
      102
    5. 5
      snowy owl
      97
  • Tell a friend

    Love Neowin? Tell a friend!