Hello all,
Im trying to figure out why my function is behaving diffrently then i expect Im still learning and appreciate any advice given.
I have some code that creates a session into a few computers then tests ports being open and returns the status.
if I run the code top down (non function) it works fine. If i run it inside of a function it creates the sesion and completes but i get no output. I am rather new to functions so it may be a beginners mistake thanks in advance . code is below
-
Working copy
start-transcript -path c:\logs\ports.txt
$s = New-PSSession server1,Server2
Invoke-Command -Session $s -ScriptBlock {
$hostname = Hostname
$ComputerName = (“comp1”,“comp2”,“comp3”)
$Ports = (“8005”)
foreach ($Computer in $ComputerName)
{
foreach ($Port in $Ports)
{
Create a Net.Sockets.TcpClient object to use for
checking for open TCP ports.
$Socket = New-Object Net.Sockets.TcpClient
Suppress error messages
$ErrorActionPreference = ‘SilentlyContinue’
Try to connect
$Socket.Connect($Computer, $Port)
Make error messages visible again
$ErrorActionPreference = ‘Continue’
Determine if we are connected.
if ($Socket.Connected)
{
“$hostname ${Computer}: Port $Port is open”
$Socket.Close()
}
else
{
“$hostname ${Computer}: Port $Port is closed or filtered”
}
Apparently resetting the variable between iterations is necessary.
$Socket.Dispose()
$Socket = $null
}
}
exit
}Stop-Transcript
Get-PSSession|Remove-PSSession
-
Non-working code
Function test-port
{
param ([string]$session,$ComputerName,[int]$ports)
$s = New-PSSession $session
Invoke-Command -Session $s -ScriptBlock {
foreach ($Computer in $ComputerName)
{
foreach ($Port in $Ports)
{
Create a Net.Sockets.TcpClient object to use for
checking for open TCP ports.
$Socket = New-Object Net.Sockets.TcpClient
Suppress error messages
$ErrorActionPreference = ‘SilentlyContinue’
Try to connect
$Socket.Connect($Computer, $Port)
Make error messages visible again
$ErrorActionPreference = ‘Continue’
Determine if we are connected.
if ($Socket.Connected)
{
“$hostname ${Computer}: Port $Port is open”
$Socket.Close()
}
else
{
“$hostname ${Computer}: Port $Port is closed or filtered”
}
Apparently resetting the variable between iterations is necessary.
$Socket.Dispose()
$Socket = $null
}
}
exit
} -ArgumentList $ComputerName,$Ports
}
$session = “serv1”,“serv2”,“serv3”
$ComputerName = (“comp1”)
$Ports = (“6379”)
test-port -session $session -ComputerName $ComputerName -ports $Ports