0

I am using below Powershell code to query an FTP folder and get the name of the existing file. However, I am not getting the desired output. I get some unwanted results from the code. I appreciate some help in getting the file name only.

Code:

$username='Th1sUser'
$password='Th1sPas3'
$ftpuri='ftp://repo.ftpserver.com/Installer'

$uri=[system.URI] $ftpuri
$ftprequest=[system.net.ftpwebrequest]::Create($uri)

$ftprequest.Credentials=New-Object System.Net.NetworkCredential($username,$password)

$ftprequest.Method=[system.net.WebRequestMethods+ftp]::ListDirectory
$response=$ftprequest.GetResponse()
$strm=$response.GetResponseStream()

$reader=New-Object System.IO.StreamReader($strm,'UTF-8')
$list=$reader.ReadToEnd()

Write-Host "$list"

Result:

Installer/.
Installer/..
Installer/Installerv1.exe

I would like to get the installerv1.exe as the file name. Also is there a possibility to get the most recent .exe name from that directory if there are multiple files and get that file name? Thank you in advance.

user25998
  • 15
  • 3

1 Answers1

0

You will have to parse the ftp response in order to extract the information you need.

For example, if you need the filename of a line, you can simply loop through the response (line by line) and split the line (which creates an array) and get the last item;

ResponselineAsString.split("/")[-1] 

[-1] being the last member of the array

Note: This doesn't tell you if it's a file or a directory

If you need the most recent file in a folder, you have at least two ways to achieve this:

While looping through the lines in the response, you can call [WebRequestMethods.Ftp]::GetDateTimestamp for each file and then do a comparison in your script.

Or you can call [WebRequestMethods.Ftp]::ListDirectoryDetails instead of [WebRequestMethods.Ftp]::ListDirectory.

You can find a good example of how to process the response of ListDirectoryDetails using regular expressions in the following article: Parsing FtpWebRequest ListDirectoryDetails line

It will provide you with all information you need (dir or file, permissions, date time, etc) and then put the logic you want in your script.

ZivkoK
  • 366
  • 3
  • 6