Create a variable from a Remote Ping Response IP Address - powershell

I need to be able to ping a range of IP addresses and when I get a reply on one, then capture that IP to put in a variable which I can use to update the local computers host file.
The purpose of this script is to be used for a Point-to-Site Azure VPN service. A remote server is connecting as a client and is given a second IP address which changes on each connection. The other server can only communicate to the remote server on this IP address, but the application it uses only uses DNS Names, so I will need to update the hosts file with the connecting servers IP each time it dials in.
$subnet = "172.16.201.0"
$start = 1
$end = 10
$ping = 1
while ($start -le $end) {
$IP = "172.16.201.$start"
Write-Host "Pinging $IP" -ForegroundColor Cyan
Test-Connection -ComputerName $IP -count 1 -Quiet
$start++
}
So far the above code only does a IP Sweep and outputs the success/failure of each IP. I need to capture the success IP and put that in a variable

i presume you want only the 1st responding IP address, not all the addresses in the range. [grin] you can turn this into a function fairly easily. you can also turn OFF the verbose output by commenting out the 2nd line.
$Old_VPref = $VerbosePreference
$VerbosePreference = 'Continue'
$Subnet = '192.168.1'
$RangeStart = 60
$RangeEnd = 69
$1stRespondingIPv4 = foreach ($Octet in $RangeStart..$RangeEnd)
{
$IP = $Subnet, $Octet -join '.'
$WV_Msg = 'Testing {0} ...' -f $IP
Write-Verbose -Message $WV_Msg
$Pingable = Test-Connection -ComputerName $IP -Count 1 -Quiet
if ($Pingable)
{
$IP
# the next line stops the foreach loop
break
}
}
''
$1stRespondingIPv4
$VerbosePreference = $Old_VPref
output ...
VERBOSE: Testing 192.168.1.60 ...
VERBOSE: Testing 192.168.1.61 ...
VERBOSE: Testing 192.168.1.62 ...
VERBOSE: Testing 192.168.1.63 ...
VERBOSE: Testing 192.168.1.64 ...
192.168.1.64

$dns = "domain.com"
$ipAddresses = #(
"172.16.201.0"
"172.16.201.1"
"172.16.201.2"
"172.16.201.3"
"172.16.201.4"
"172.16.201.5"
"172.16.201.6"
"172.16.201.7"
"172.16.201.8"
"172.16.201.9"
"172.16.201.10"
)
foreach($ip in $ipAddresses) {
Write-Host "Pinging $ip" -ForegroundColor Cyan
$ping = Test-Connection -ComputerName "$ip" -count 1 -Quiet
if ($ping) {
Add-Content -Path "C:\Windows\System32\drivers\etc\hosts" -Value "$ip $dns"
Write-Host "The host file was updated with the successful IP and hostname: $ip $dns" -ForegroundColor Cyan
}
}

Related

Change IP as user with powershell script on Win 7

On my Windows 7 Embedded machine I want to change the IP address via Powershell script as an user.
For that I added my user to the "Network Configuration Operators" group and wrote the following script.
param(
[string]$Type
)
Write-Host "Networkchanger"
$adapter = Get-WmiObject win32_NetworkAdapterConfiguration -filter "Index = 11"
if($Type -eq "black"){
Write-Host "Using black"
$IP = "192.168.1.172"
$Netmask = "255.255.255.0"
$Gateway = "192.168.1.1"
$DNS = "192.168.1.254"
$adapter.EnableStatic($IP, $NetMask)
Sleep -Seconds 4
$adapter.SetGateways($Gateway)
$adapter.SetDNSServerSearchOrder($DNS)
} else {
Write-Host "Using rf"
$adapter.SetDNSServerSearchOrder()
$adapter.EnableDHCP()
}
The script runs fine as admin, but not as an user. Did I forget to add some rights to the script or user?
Edit:
When I click "Run as admin" and use black it works for the first time. After changing it to rf (which works), the black net just changes the Gateway and DNS, but not the IP and Netmask, which confuses me.
You are correct that admin rights are required for setting a static IP address. I do it on our Windows Embedded Standard 7 images. Essentially, I created a shortcut on the desktop with Run As Administrator for launching PowerShell with the particular script. Also note that no such elevated permission is required to enable DHCP, but it doesn't hurt.
There is a slightly simpler way to set the IP address from PowerShell, using the netsh command. The good thing about this approach is that you can see the specific error from a command prompt also. Try switching back and forth from an elevated command prompt and a non-elevated one.
netsh interface ip set address "${InterfaceName}" static addr=${IPAddr} mask=${Mask} gateway=${Gateway}
netsh interface ip set address "${InterfaceName}" dhcp
I've solved the problem by heavily modifing my Powershell script:
$id=[System.Security.Principal.WindowsIdentity]::GetCurrent()
$principal=New-Object System.Security.Principal.WindowsPrincipal($id)
if(!$principal.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)) {
$powershell=[System.Diagnostics.Process]::GetCurrentProcess()
$psi=New-Object System.Diagnostics.ProcessStartInfo $powershell.Path
$script=$MyInvocation.MyCommand.Path
$prm=$script+$Type
foreach($a in $args) {
$prm+=' '+$a
}
$psi.Arguments=$prm
$psi.Verb="runas"
[System.Diagnostics.Process]::Start($psi) | Out-Null
return;
}
Write-Host "Networkchanger"
Write-Host ""
Write-Host "[0] cancel"
Write-Host "[1] net1: 10.0.0.172"
Write-Host "[2] net2: 192.168.178.(172,235,237,248,251)"
$adapter = Get-WmiObject win32_NetworkAdapterConfiguration -filter "Index = 0"
$loop = 1;
while($loop -eq 1){
$Type = Read-Host -Prompt '0, 1 OR 2'
switch($Type){
0 {
Write-Host "Cancel Process"
Sleep -Seconds 3
exit
}
1 {
Write-Host "Using sb"
$IP = "10.0.0.172"
$Netmask = "255.255.255.0"
$Gateway = "10.0.0.1"
$DNS = "10.0.0.254"
$adapter.EnableStatic($IP, $NetMask)
Sleep -Seconds 4
$adapter.SetGateways($Gateway)
$adapter.SetDNSServerSearchOrder($DNS)
$loop = 0
}
2 {
Write-Host "Using rf"
$macaddress = $adapter | select -expand macaddress
Write-Host $macaddress
$IP = ""
if ($macaddress -eq "xx:xx:xx:xx:xx:xx"){
$IP = "192.168.178.172"
} elseif ($macaddress -eq "xx:xx:xx:xx:xx:xx") {
$IP = "192.168.178.235"
} elseif ($macaddress -eq "xx:xx:xx:xx:xx:xx") {
$IP = "192.168.178.237"
} elseif ($macaddress -eq "xx:xx:xx:xx:xx:xx") {
$IP = "192.168.178.248"
} elseif ($macaddress -eq "xx:xx:xx:xx:xx:xx") {
$IP = "192.168.178.251"
} else {
Write-Host "Mac address not in list"
Sleep -Seconds 5
exit
}
$Netmask = "255.255.255.0"
$Gateway = "192.168.178.1"
$DNS = "192.168.178.2","192.168.178.3"
$adapter.EnableStatic($IP, $NetMask)
Sleep -Seconds 4
$adapter.SetGateways($Gateway)
$adapter.SetDNSServerSearchOrder($DNS)
$loop = 0
}
}
}
Write-Host "Current IP: "
ipconfig
Start-Sleep -seconds 5

Powershell to find out disconnected RDP session and log off at the same time

Is there a script that can log out my disconnected RDP session from any server? This is causing a lot of pain and constant ad account lockouts.
Any help would be awesome.
I have got the answer and I am writing this answer to help someone in need as I had to figure this out myself. I created a script using online resources to find out disconnected RDP sessions on all Windows Server in my AD environment. I run a query on each Windows Server and create a CSV formatted list, I then use that list to log out my ID from those servers, so I don't have any disconnected sessions.
I did this to make sure my AD account doesn't get locked out due to some disconnected RDP sessions when its time to change my password.
You are free to modify this script as per your need.
Script Code is below:
param (
#get current logged on username
[string]$UserName = $env:USERNAME
)
# Import the Active Directory module for the Get-ADComputer CmdLet
Import-Module ActiveDirectory
# Query Active Directory for enabled windows servers computer accounts and sort by name
$Servers = Get-ADComputer -Filter {(OperatingSystem -like "*windows*server*") -and (Enabled -eq "True")} | Sort Name
# Initiating variables
$SessionList = $NULL
$queryResults = $NULL
$SError = $null
$SDown = $null
$z = 0
# Get total number of servers
$count = $Servers.count
# Start looping through each server at a time
ForEach ($Server in $Servers) {
# initiate counter for showing progress
$z = $z + 1
$ServerName = $Server.Name
# Start writing progress
Write-Progress -Activity "Processing Server: $z out of $count servers." -Status " Progress" -PercentComplete ($z/$Servers.count*100)
# check if server is pingable before running the query on the server
if (Test-Connection $Server.Name -Count 1 -Quiet) {
Write-Host "`n`n$ServerName is online!" -BackgroundColor Green -ForegroundColor Black
Write-Host ("`nQuerying Server: `"$ServerName`" for disconnected sessions under UserName: `"" + $UserName.ToUpper() + "`"...") -BackgroundColor Gray -ForegroundColor Black
# Store results in array
[array]$queryResults += (
# Query server for specific username
query user $UserName /server:$ServerName |
foreach {
# Look for lines with Disc string to filter out active sessions
if ($_ -match "Disc") {
# format the output in CSV by replacing more than 2 spaces with a comman
write-output ("`n$ServerName," + (($_.trim() -replace ' {2,}', ',')))
}
}
)
}
# If server is not pingable show error message
else {
# Make list of server that are down.
[array]$SDown += ($ServerName)
Write-Host "`nError: Unable to connect to $ServerName!" -BackgroundColor red -ForegroundColor white
Write-Host "Either the $ServerName is down or check for firewall settings on server $ServerName!" -BackgroundColor Yellow -ForegroundColor black
}
}
# If there are some non pingable server then display the list
if ($SDown -ne $null -and $SDown) {
Write-Host "`nScript was unable to connect to the following server:" -ForegroundColor White -BackgroundColor Red
$SDown
}
# Check if any disconnected session are stored in the array
if ($queryResults -ne $null -and $queryResults) {
# Convert the CSV fromat to table format with headers
$QueryResultsCSV = $queryResults | ConvertFrom-Csv -Delimiter "," -Header "ServerName","UserName","SessionID","CurrentState","IdealTime","LogonTime"
# Show the results on console
$QueryResultsCSV |ft -AutoSize
# Go through each Disconnected session stored in the array
$QueryResultsCSV | foreach {
# Grabb session ID and ServerName
$Sessionl = $_.SessionID
$Serverl = $_.ServerName
# Show message on the console
Write-Host "`nLogging off"$_.username"from $serverl..." -ForegroundColor black -BackgroundColor Gray
sleep 2
# Logout user using session ID
logoff $Sessionl /server:$Serverl /v
}
}
else {
# if array is empty display message that no session were found
Write-Host `n`n`n`n("*" * $LineSize)
Write-Host "You are all good! No ghost sessions found!" -BackgroundColor Green -ForegroundColor Black
Write-Host ("*" * $LineSize)
}
# Pause at the end so you can capture the output
$null = Read-Host "`n`nScript execution finished, press enter to exit!"
Screenshots:
When the script is running on through all server, shows you online and offline servers:
List of servers that Script was unable to connect:
The script lists the servers where it found disconnected RDP sessions.
When script start to log your disconnected sessions off and it pauses at the end.
Thank you for your sample code. I have created a simplified code to logoff all disconnected users in the same server
$hostname = hostname
if (Test-Connection -ComputerName $hostname -Quiet -Count 1){
$result = query session /server:$hostname
$rows = $result -split "`n"
foreach ($row in $rows) {
if ($row -NotMatch "services|console" -and $row -match "Disc") {
$sessionusername = $row.Substring(19,20).Trim()
$sessionid = $row.Substring(39,9).Trim()
Write-Output "Logging Off RDP Disconnected Sessions User $sessionusername"#, $session[2], $session[3]"
logoff $sessionid /server:$hostname
}
}
}

Powershell - Test-Connection failed due to lack of resources

Test-connection intermittently fails with a lack of resources error:
test-connection : Testing connection to computer 'SOMESERVER' failed: Error due to lack of resources
At line:1 char:45
+ ... ($server in $ServersNonProd.Name) { test-connection $server -Count 1}
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ResourceUnavailable: (SOMESERVER:String) [Test-Connection], PingException
+ FullyQualifiedErrorId : TestConnectionException,Microsoft.PowerShell.Commands.TestConnectionCommand
As a result, it's not reliable and fairly useless when you need to test a list of computers in a loop. Is there a fix, alternative, or workaround to get this functionality reliably?
This is my current solution, but it's still not sufficiently reliable (sometimes they still fail 5 times in a row) and it takes forever because of all the delays and retries.
$Servers = Import-CSV -Path C:\Temp\Servers.csv
$result = foreach ($Name in $Servers.FQDN) {
$IP = $null
if ( Resolve-DNSName $Name -ErrorAction SilentlyContinue ) {
$IP = (Test-Connection -Count 1 -ComputerName $Name -ErrorAction SilentlyContinue).IPv4Address
if ( $IP -eq $null ) {
Start-Sleep -Milliseconds 100
$IP = (Test-Connection -Count 1 -ComputerName $Name -ErrorAction SilentlyContinue).IPv4Address
}
if ( $IP -eq $null ) {
Start-Sleep -Milliseconds 200
$IP = (Test-Connection -Count 1 -ComputerName $Name -ErrorAction SilentlyContinue).IPv4Address
}
if ( $IP -eq $null ) {
Start-Sleep -Milliseconds 300
$IP = (Test-Connection -Count 1 -ComputerName $Name -ErrorAction SilentlyContinue).IPv4Address
}
if ( $IP -eq $null ) {
Start-Sleep -Milliseconds 400
$IP = (Test-Connection -Count 1 -ComputerName $Name -ErrorAction SilentlyContinue).IPv4Address
}
}
new-object psobject -Property #{FQDN = $Name; "IP Address" = $IP}
}
A normal ping (ping.exe) works every time, so if there's a good way to parse that with powershell (host up or down, what IP is responding), that seems like the ideal solution, but I just need something that works, so I'm open to ideas.
In newer versions of PowerShell, the -Quiet parameter on Test-Connection does seem to always return either True or False. It didn't seem to work consistently on older versions, but either I'm doing something differently now or they've improved it:
$Ping = Test-Connection -ComputerName $ComputerName -Count 1 -Quiet
I haven't tested it recently when the network is simply unavailable, however.
Older answer:
Test-Connection doesn't respond well when DNS doesn't respond with an address or when the network is unavailable. That is, if the cmdlet decides it can't send the ping at all, it errors in unpleasant ways that are difficult to trap or ignore. Test-Connection is only useful, then, when you can guarantee that DNS will resolve the name to an address, and that the network will always be present.
I tend to use CIM Pings (Powershell v3+):
$Ping2 = Get-CimInstance -ClassName Win32_PingStatus -Filter "Address='$ComputerName' AND Timeout=1000";
Or WMI pings (Powershell v1 or v2):
$Ping = Get-WmiObject -Class Win32_PingStatus -Filter "Address='$ComputerName' AND Timeout=1000";
Either of which are basically the same, but return slightly different formats for things. Note that Get-WmiObject is not available at all beginning in Powershell v6 because Get-CimInstance was designed to supersede it.
The main disadvantage here is that you have to resolve the status code yourself:
$StatusCodes = #{
[uint32]0 = 'Success';
[uint32]11001 = 'Buffer Too Small';
[uint32]11002 = 'Destination Net Unreachable';
[uint32]11003 = 'Destination Host Unreachable';
[uint32]11004 = 'Destination Protocol Unreachable';
[uint32]11005 = 'Destination Port Unreachable';
[uint32]11006 = 'No Resources';
[uint32]11007 = 'Bad Option';
[uint32]11008 = 'Hardware Error';
[uint32]11009 = 'Packet Too Big';
[uint32]11010 = 'Request Timed Out';
[uint32]11011 = 'Bad Request';
[uint32]11012 = 'Bad Route';
[uint32]11013 = 'TimeToLive Expired Transit';
[uint32]11014 = 'TimeToLive Expired Reassembly';
[uint32]11015 = 'Parameter Problem';
[uint32]11016 = 'Source Quench';
[uint32]11017 = 'Option Too Big';
[uint32]11018 = 'Bad Destination';
[uint32]11032 = 'Negotiating IPSEC';
[uint32]11050 = 'General Failure'
};
$StatusCodes[$Ping.StatusCode];
$StatusCodes[$Ping2.StatusCode];
Alternately, I've used .Net Pings like #BenH described, too, which does a lot of that work for you. There was a reason I stopped using them in favor of WMI and CIM, but I can no longer remember what that reason was.
I am partial to using the .Net Ping class rather than Test-Connection
$Timeout = 100
$Ping = New-Object System.Net.NetworkInformation.Ping
$Response = $Ping.Send($Name,$Timeout)
$Response.Status
Note that the Send method can take additional parameters if you need to set TTL/Fragmentation. Also timeout is in milliseconds, with just $name the timeout I think is 5 seconds, which is usually too long.
Windows IP Helper defines IP_REQ_TIMED_OUT error to value 11010 wich is the same as Windows system error WSA_QOS_ADMISSION_FAILURE 11010 'Error due to lack of resources.'
so it is likely that what actually received in questioned case was time out error and simply misinterpreted as 'lack of resources'.
powershell v7 does not suffer from this issue when using test-connection
I'm going to cheat and use powershell 7. Microsoft is always unpingable.
test-connection -count 1 yahoo.com,microsoft.com | select destination,status
Destination Status
----------- ------
yahoo.com Success
microsoft.com TimedOut
Or multi-threaded:
echo yahoo.com microsoft.com | % -parallel { test-connection -count 1 $_ } |
select destination,status
Destination Status
----------- ------
yahoo.com Success
microsoft.com TimedOut
,'microsoft.com' * 10 | % -parallel { test-connection -count 1 $_ } |
select destination,status
Destination Status
----------- ------
microsoft.com TimedOut
microsoft.com TimedOut
microsoft.com TimedOut
microsoft.com TimedOut
microsoft.com TimedOut
microsoft.com TimedOut
microsoft.com TimedOut
microsoft.com TimedOut
microsoft.com TimedOut
microsoft.com TimedOut
# one time takes like 4 seconds
measure-command { ,'microsoft.com' * 10 | % -parallel { test-connection -count 1 $_ } |
select destination,status } | % seconds
9
I see this error when (in 5.x anyway) i include -computername in test-connection.
remove that and it works. The other thing about using ping vs test-connection, ICMP is blocked by default with the windows firewall where test-connection does the equivalent of the win32_pingstatus command. WMI is not blocked by default. However, if the WMI repository on the system is not healthy (or blocked by fw) it will of course fail.

Batch file that change dns between 2 option

I'm trying to make a windows 10 batch file that swap my dns from 2 options. The first one is 8.8.8.8 (google dns) and the second one are a custom DNS that allows me to watch US netflix (like 90.90.90.90).
The bash command to change dns is
netsh interface ipv4 add dnsserver "Ethernet" address=8.8.8.8 index=1
the command to check which dns is up and running is:
nslookup
Now i want to do an IF THEN ELSE that work like this:
if (dns == 8.8.8.8)
then (change them to 90.90.90.90)
else (change them to 8.8.8.8)
Even a powershell script is fine
This should work:
#echo off
set "dns=8.8.8.8"
for /F "skip=1 tokens=2" %%a in ('nslookup^<NUL') do if "%%a" equ "8.8.8.8" set "dns=90.90.90.90"
netsh interface ipv4 add dnsserver "Ethernet" address=%dns% index=1
Basically:
# Setup the dos command process information:
$pinfo = New-Object System.Diagnostics.ProcessStartInfo
$pinfo.FileName = "nslookup"
$pinfo.Arguments = ""
$pinfo.UseShellExecute = $false
$pinfo.CreateNoWindow = $true
$pinfo.RedirectStandardOutput = $true
$pinfo.RedirectStandardError = $true
# Start the process:
$process.Start() | Out-Null
# Wait a while for the process to do something:
sleep -Seconds 5
# If the process is still active kill it:
if (!$process.HasExited) {
$process.Kill()
}
# get output from stdout and stderr:
$stdout = $process.StandardOutput.ReadToEnd()
$stderr = $process.StandardError.ReadToEnd()
# Parse the IP address from the output:
$regex = [regex] "\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b"
$regex.Matches($stdout) | %{ $Condition = $_.value }
# Do your dns change based on the output:
if ($Condition -eq "8.8.8.8")
{
"set other dns"
}
Else
{
"set google dns"
}
Sorry I couldn't mature the answer a bit more; unexpected visitors.
-Edit:
Taking into account some of the comments, and a bug with my regular expression, this might be a more suitable solution:
[cmdletbinding()]
param ([parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] [string[]]$ComputerName = $env:computername )
begin {}
process {
# get current DNS setting:
foreach ($Computer in $ComputerName) {
if(Test-Connection -ComputerName $Computer -Count 1 -ea 0)
{
try {
$Networks = Get-WmiObject Win32_NetworkAdapterConfiguration -ComputerName $Computer -EA Stop | ? {$_.IPEnabled}
}
catch
{
Write-Warning "Error occurred while querying $computer."
Continue
}
foreach ($Network in $Networks)
{
$Condition = $Network.DNSServerSearchOrder;
break;
}
}
}
# Do your dns change based on the output:
if ($Condition -eq "8.8.8.8")
{
"set other dns";
}
Else
{
"set google dns";
}
}
end {}

How can I automate Telnet port checking in Powershell?`

I'm currently trying to put together a script that queries AD for a list of computers, pings the computers to determine which ones are still active, and then telnets into a specific port on all the pingable computers. The output I'm looking for is a full list of pingable computers in AD for which I can't telnet to the said port.
I've read these few questions, but they don't quite hit on what I'm trying to do. I just want to see if the telnet connection is successful without entering telnet (or automate the quitting of telnet) and move on to the next machine to test. The AD and pinging portions of my script are set, I'm just stuck here. The things I've tried haven't quite worked as planned.
Here is the code for the first parts of the script, if needed:
Get-ADComputer -Filter * -SearchBase 'DC=hahaha,DC=hehehe' | ForEach {
$computerName = $_.Name
$props = #{
ComputerName = $computerName
Alive = $false
PortOpen = $false
}
If (Test-Connection -ComputerName $computerName -Count 1 -Quiet) {
$props.Alive = $true
}
Adapting this code into your own would be the easiest way. This code sample comes from the PowerShellAdmin wiki. Collect the computer and port you want to check. Then attempt to make a connection to that computer on each port using Net.Sockets.TcpClient.
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) {
"${Computer}: Port $Port is open"
$Socket.Close()
}
else {
"${Computer}: Port $Port is closed or filtered"
}
# Apparently resetting the variable between iterations is necessary.
$Socket = $null
}
}
Here is a complete powershell script that will:
1. read the host and port details from CSV file
2. perform telnet test
3. write the output with the test status to another CSV file
checklist.csv
remoteHost,port
localhost,80
asdfadsf,83
localhost,135
telnet_test.ps1
$checklist = import-csv checklist.csv
$OutArray = #()
Import-Csv checklist.csv |`
ForEach-Object {
try {
$rh = $_.remoteHost
$p = $_.port
$socket = new-object System.Net.Sockets.TcpClient($rh, $p)
} catch [Exception] {
$myobj = "" | Select "remoteHost", "port", "status"
$myobj.remoteHost = $rh
$myobj.port = $p
$myobj.status = "failed"
Write-Host $myobj
$outarray += $myobj
$myobj = $null
return
}
$myobj = "" | Select "remoteHost", "port", "status"
$myobj.remoteHost = $rh
$myobj.port = $p
$myobj.status = "success"
Write-Host $myobj
$outarray += $myobj
$myobj = $null
return
}
$outarray | export-csv -path "result.csv" -NoTypeInformation
result.csv
"remoteHost","port","status"
"localhost","80","failed"
"asdfadsf","83","failed"
"localhost","135","success"