Pages

Friday, August 25, 2017

Test TCP Ports on multiple servers

Test Connectivity of TCP Ports on remote machine(s)

Starting from PowerShell 4.0 We have got a pretty neat cmdlet that is Test-NetConnection which works for testing TCP Ports as well as does a ping test on remote endpoints (servers).

Ex: PS C:\> Test-NetConnection localhost -Port 3389

The only drawback with Test-NetConnection is that it does not have a parameter for specifying TimeOut value to return the result or fail if a response is not received within 'x' milliseconds which is very time consuming and sometimes frustrating while doing port connectivity test for bulk hosts.

Here is a Quick PowerShell Function which can be used to test TCP ports on Remote Endpoints with complete control at your fingertips which lets you specify whatever TimeOut period you want it to return after getting a response or connection refusal from the target.

function Test-Port {
Param($HostName, $TcpPort, $MsTimeOut)
$tcpClient = New-Object System.Net.Sockets.TcpClient
$connection = $tcpClient.BeginConnect($HostName,$TcpPort,$null,$null)
$asyncResult = $connection.AsyncWaitHandle.WaitOne($MsTimeOut,$false)
"$HostName : $TcpPort : $asyncResult"
}

Now that we have the function ready but we wont be able to use it simply as a PowerShell Script as its written as a function which would need to be loaded into memory before being able to execute it.

The best thing with PowerShell Functions is, it is used as a simple cmdlet instead of a being used as a PowerShell Script and you don’t really need to bother where it located to be able to execute it. It just has one caveat which is loading it in memory which is also called Dot Sourcing.

How do we do Dot sourcing?
  • Just copy the code and save it as a PS1 Script (Test-Port.ps1)
  • Execute it prefixing with an extra dot “.” (Eg.  PS C:\>. .\Test-Port.ps1 )
  • Done!!

Now name of the function should be available as a PowerShell cmdlet in that specific PowerShell Window. 
Remember that this cmdlet will only be available in that specific PowerShell console as the Function has only been loaded in that specific PowerShell Console. But wait.. there is workaround too, We can get all our functions loaded in every PowerShell console we launch.
How to do that :
·        Open a Powershell Console.
·        Type $PROFILE and hit enter, It will display a PS1 File under your home directory:
PS C:\> $PROFILE
C:\Users\prakakum\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1
·        Open this ps1 PS Profile script in notepad/ISE/any text editor and add whatever functions you have to it. For example we will add this Test-Port Function here.
 
       
     Save and close the File, Now every PowerShell Console we open should have this function available as a native cmdlet.

  

Here is how we can use this function (any function) to run on multiple servers from a text file.

Thank You :)
Post your comments/suggestions below

Monday, July 17, 2017

Get uptime of ESX hosts from one or more Virtual Center




Get uptime of ESXi hosts from one or more Virtual Center

Here is a small script which can get number of days for which ESXi hosts are up in your Virtual Center.

########################################################################################
##The script is used for getting ESX Hosts uptime information from Virtual Center(S). ##
##It gets Uptime information of ESX hosts from Virtual Center and shows it on console ##
##It also exports the uptime and overall status of ESXi hosts in CSV.                 ##  
########################################################################################

##Set initial Variables for use in the Script.
$Path = "C:\TEMP"
$DateF = Get-Date -Format yyyy-MM-dd-HH-mm
$LoginUsr = "UserName"
$LoginPWD = "Password"

#Get Today's Date calculation to find out number of days the Host has been up.
$Today = Get-Date

##List of Virtual Center Servers to get detials from.
$VirtualCenters = "VC1.domain.com", "vc2.domain.com"

##Loop through each Virtual center defined in above array of VCs.
$VirtualCenters | foreach {
    $VCName = $_
    Connect-VIServer $VCName -User $LoginUsr -Password $LoginPWD -AllLinked:$True

    $Result = Get-VMHost |select Name, @{N="Uptime"; E={(New-TimeSpan $_.ExtensionData.Summary.Runtime.BootTime $Today).Days}},`
     @{N="OverAllStatus"; E={$_.extensionData.OverAllStatus}},`
     @{N="VCName"; E={$VCName}}
   $Result | Format-Table -AutoSize
   $Result | Export-Csv -NoTypeInformation -UseCulture $Path\ESXHost-Uptime-$Datef.csv
  }

##End of Code

Tuesday, April 11, 2017

Check Availability of a Share Path using PowerShell

Check Availability of a Share Path and log output to a text file located on that share:

Here is a simple PowerShell script which checks if a particular Network path (SMB Share/File Share/NAS or SAN  originating path) is online and reachable or not. It Writes a text file at the target location and keeps logging information at every fixed interval which can later be used to analyze availability of the target location.

######################################################################################
# This script checks availability of a Share at given interval and writes output     #
# in the file at that same shared location.                                          #
# Change the FileShare / SMB / NAS /SAN storage path in the variable path.           #
# Sleep timing (start-sleep) to check at whatever specific interval you want.        #
######################################################################################

## Main Loop to start and run endlessly :
for ($i = 1; $i -gt 0; $i++) {

## Take the Date_time variable to be used to write log in the output file:
 $Now = Get-Date -Format yyyy_MM_dd_hh:mm:ss

## Path of the Share along with file name which you want to check and log output to:
 $FilePath = "\\SharePath\d\logs\TestFile.txt"
        if (Test-Path $FilePath )
            { Write-Output "Share is alive at $Now" >> $FilePath }
        else { New-Item -ItemType "File" -Path $FilePath; Write-Output "Share is alive at $Now" >> $FilePath }

## Time to sleep and check again (3600 = 1 Hour) Convert the duration i seconds and put in at the below line:
 Start-Sleep -Seconds 3600
}

# Points to consider:
* Make sure this script is run from a location from where you want to check the availability of share.
* User running this script should have enough rights to create file on the target location.