PowerShell Tip of the Week: File browser

Today’s tip will be about file browser in PowerShell. Its a nice feature where you can just select the server list instead of writing path inside the code.

File browser

To select the file we’re gonna use System.Windows.Forms. The System.Windows.Forms namespace contains classes for creating Windows-based applications that take full advantage of the rich user interface features available in the Microsoft Windows operating system. For more information please visit technet site.

In this code I used filter parameter to determine which type of files do I want to search:

#Browsing file
Add-Type -AssemblyName System.Windows.Forms
$FileBrowser = New-Object System.Windows.Forms.OpenFileDialog
$FileBrowser.filter = "Txt (*.txt)| *.txt"
[void]$FileBrowser.ShowDialog()
$FileBrowser.FileName
file browser
file browser

Below you can find file browser example where you have to select servers list in txt format. Additionally script will check if server exist and run ping connectivity test against:

#Ping class
$Ping = New-Object System.Net.NetworkInformation.Ping
$PingStatus = ($Ping.Send("$Server").Status)
$PingStatus

#Checking if server exist in our network
$DNSCheck = ([System.Net.Dns]::GetHostByName(("$Server")))
$DNSCheck.hostname

Final script:

$ErrorActionPreference = "Stop"
$Array = @()

#Browsing file
Add-Type -AssemblyName System.Windows.Forms
$FileBrowser = New-Object System.Windows.Forms.OpenFileDialog
$FileBrowser.filter = "Txt (*.txt)| *.txt"
[void]$FileBrowser.ShowDialog()

#Getting servers from txt file
Try
{
    $FilePath = $FileBrowser.FileName
    $Servers = Get-Content -Path $FilePath
}
Catch
{
  $_.Exception.Message
  Break
}

#Proceed if file exist
If( !$Servers )
{
    Write-Warning "Something went wrong"
}
Else
{
    #Ping class
    $Ping = New-Object System.Net.NetworkInformation.Ping

    #Looping each server from the list
    Foreach( $Server in $Servers )
    {
        $Server = $Server.Trim()
        Write-Host Processing $Server

        $PingStatus = $null
        $DNSCheck = $null
        $Object = $null

        #Checking if server exist in our network
        Try
        {
            $DNSCheck = ([System.Net.Dns]::GetHostByName(("$Server")))
        }
        Catch
        {
            $_.Exception.Message
            Continue
        }

        If($DNSCheck)
        {
            $PingStatus = ($Ping.Send("$Server").Status)

            $Object = New-Object PSObject -Property ([ordered]@{ 
      
                "Server name"             = $DNSCheck.hostname
                "Ping Status"             = $PingStatus
            })

            $Array += $Object
        }
    }
}

Write-Host `nFinal results: -ForegroundColor Yellow
$Array
File Browser script
File Browser script

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.