Home > Back-end >  Powershell parameters passing in for loop to function
Powershell parameters passing in for loop to function

Time:09-25

i'm new to powershell, i have a specific task and would like to create a port scanner in powershell that allows to pass parameters in a foreach loop to a specific parameter in the function.

The function is called testport, the specific parameter i would like to pass when running the function in a for loop is $a - which would be a list of IP's i'm interested in scanning. Here's the function:

function testport ($hostname='10.0.0.$a',$port=445,$timeout=100) {
$requestCallback = $state = $null
$client = New-Object System.Net.Sockets.TcpClient
$beginConnect = $client.BeginConnect($hostname,$port,$requestCallback,$state)
Start-Sleep -milli $timeOut
if ($client.Connected) { $open = $true } else { $open = $false }
$client.Close()
[pscustomobject]@{hostname=$hostname;port=$port;open=$open}

the foreach loop to run the function would look like this:

foreach ($a in 1..255) {testport}

when ran, it runs against 10.0.0.$a multiple times, instead of 10.0.0.1, 10.0.0.2 etc. How can i make this run properly?

CodePudding user response:

You cant use $a in your functions $hostname parameter default value as $a doesnt exist until powershell gets to the foreach statement (after its already read your function). At best $a will already exist and have some unknown value, or it wont exist at all - either way you get the wrong output. Your on the right lines, but you need to make some adjustments...

I would advise you make your testing function generic (so it accepts a normal IP), then in your for loop put your logic to generate the IPs to scan.

So your for loop might look something like:

foreach ($a in 1..255) {
  Write-Host "Testing ports on 10.0.0.$a";
  testport -hostname "10.0.0.$a"
}

Then i would alter the function signature to remove $hostname's default value ('10.0.0.$a'). Your testport function declaration should look like this:

function testport ($hostname,$port=445,$timeout=100)

(NOTE: if you explicitly pass $hostname a value it will use that value instead of the default - but given the IP will always be different it probably doesnt make sense to give it a default value)

  • Related