I’m hoping someone could provide some guidance with a script I’ve been working on.
Objective of the script:
Select an IP from a .csv then test if it's in use with a ping.
If the IP is in use, select another and try again.
If the IP is free add it to a variable.
I've had success selecting an IP from the .cvs containing unused IPs, but I run into issues trying to get it to loop back if the IP is in use. I think my "elseif" is wrong and I'm also wondering if I even need a function?
Current version:
function get-testip {
$importPath = "C:\temp\ip.csv"
$count = 1
$list = Import-Csv -Path $importPath | Select-Object -ExpandProperty ip
The code does exactly what you was asking for. It takes one IP from the list, checks if a device is responding from that IP and if not it outputs this IP. Then it takes the next IP and so on. If you want to collect these IPs not responding you just have to put a “$Result =” in front of the “foreach” and you’re done. What’s wrong on that?
You stated “this snippet would output all IPs from the list not responding to a ping”. I only want one unused IP added to a variable. I also don’t want it to run through each IP, I want to take a random IP from the list.
If something is done in sequence it’s not random, its in sequence.
Thanks for offering to help, but as I said, what you have provided is not what I was looking for. I was looking for guidance with what I had created, not something new that doesn’t do what I need.
Thank you Olaf, I appreciate you taking the time to help me.
To answer your question, its part of a script to automate VM builds. I have VM build script written and it works. There are some parts that are going to vary each run, like IPs. The IPs that are used are not always in sequence, but sometimes go for a longtime in sequence. Choosing an IP randomly may have a better success rate than testing 10’s of IPs in sequence before finding one that is free. We will find a better solution in time, but this will do for now.
May I ask why you chose to create the script the way you have? Was my original script not able to work with some small changes? Can you advise where I was going wrong?
[quote quote=221136] …
Choosing an IP randomly may have a better success rate than testing 10’s of IPs in sequence before finding one that is free. [/quote]
Using a randomly selected element does not guarantee true randomness. In case you get the same unavailable IP addresses tested again and again and again. I’d go with the sequencial approach.
I try to follow the KISS principle. I always try to keep it as simple as possible.