Using PowerShell to test an FTP connection Using PowerShell to test an FTP connection powershell powershell

Using PowerShell to test an FTP connection


Test-NetConnection is native Powershell and can be used to test simple connectivity on FTP Port 21:

Test-NetConnection -ComputerName ftp.contoso.com -Port 21


There's nothing like FTP command "open".

But maybe you mean to just test that the server listens on FTP port 21:

try{    $client = New-Object System.Net.Sockets.TcpClient("ftp.example.com", 21)    $client.Close()    Write-Host "Connectivity OK."}catch{    Write-Host "Connection failed: $($_.Exception.Message)"}

If you want to test that the FTP server is behaving, without actually logging in, use FtpWebRequest with wrong credentials and check that you get back an appropriate error message.

try{    $ftprequest = [System.Net.FtpWebRequest]::Create("ftp://ftp.example.com")    $ftprequest.Credentials = New-Object System.Net.NetworkCredential("wrong", "wrong")     $ftprequest.Method = [System.Net.WebRequestMethods+Ftp]::PrintWorkingDirectory    $ftprequest.GetResponse()    Write-Host "Unexpected success, but OK."}catch{    if (($_.Exception.InnerException -ne $Null) -and        ($_.Exception.InnerException.Response -ne $Null) -and        ($_.Exception.InnerException.Response.StatusCode -eq             [System.Net.FtpStatusCode]::NotLoggedIn))    {        Write-Host "Connectivity OK."    }    else    {        Write-Host "Unexpected error: $($_.Exception.Message)"    }}