sbrm1
sbrm1

Reputation: 1255

PowerShell: How to access a file on an FTP server as a string?

I need to download a piece of text from an FTP server via PowerShell and get it as a string. After performing the required task, I need to upload it to the same server as a different file. The file must not be saved to the local storage at any point.

For a file on a regular HTTP server, the code would be (New-Object Net.WebClient).DownloadString($uri); for downloading and (New-Object Net.WebClient).UploadString($uri, $output);" for sending it to the server for processing via a POST request.

Upvotes: 4

Views: 5929

Answers (1)

Martin Prikryl
Martin Prikryl

Reputation: 202682

DownloadString and UploadString, as all WebClient methods, work for ftp:// URLs too:

By default, the .NET Framework supports URIs that begin with http:, https:, ftp:, and file: scheme identifiers.


So unless you need some fancy options, it's as simple as:

$webclient = New-Object System.Net.WebClient
$contents = $webclient.DownloadString("ftp://ftp.example.com/file.txt")

If you need to authenticate to the FTP server, either add credentials to the URL:

ftp://username:[email protected]/file.txt

Or use WebClient.Credentials:

$webclient = New-Object System.Net.WebClient
$webclient.Credentials = New-Object System.Net.NetworkCredential("user", "mypassword") 
$contents = $webclient.DownloadString("ftp://ftp.example.com/file.txt")

Upvotes: 4

Related Questions