Reputation: 1255
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
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:
, andfile:
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