PowerShell:如何以字符串形式访问 FTP 服务器上的文件?
PowerShell: How to access a file on an FTP server as a string?
我需要通过 PowerShell 从 FTP 服务器下载一段文本并将其作为字符串获取。执行所需任务后,我需要将其作为不同文件上传到同一服务器。任何时候都不得将文件保存到本地存储。
对于常规 HTTP 服务器上的文件,下载代码为 (New-Object Net.WebClient).DownloadString($uri);
,通过 POST 请求将其发送到服务器进行处理的代码为 (New-Object Net.WebClient).UploadString($uri, $output);"
。
DownloadString
and UploadString
, as all WebClient
方法,也适用于 ftp://
URLs:
By default, the .NET Framework supports URIs that begin with http:
, https:
, ftp:
, and file:
scheme identifiers.
因此,除非您需要一些花哨的选项,否则它很简单:
$webclient = New-Object System.Net.WebClient
$contents = $webclient.DownloadString("ftp://ftp.example.com/file.txt")
如果您需要向 FTP 服务器进行身份验证,请将凭据添加到 URL:
ftp://username:password@ftp.example.com/file.txt
$webclient = New-Object System.Net.WebClient
$webclient.Credentials = New-Object System.Net.NetworkCredential("user", "mypassword")
$contents = $webclient.DownloadString("ftp://ftp.example.com/file.txt")
我需要通过 PowerShell 从 FTP 服务器下载一段文本并将其作为字符串获取。执行所需任务后,我需要将其作为不同文件上传到同一服务器。任何时候都不得将文件保存到本地存储。
对于常规 HTTP 服务器上的文件,下载代码为 (New-Object Net.WebClient).DownloadString($uri);
,通过 POST 请求将其发送到服务器进行处理的代码为 (New-Object Net.WebClient).UploadString($uri, $output);"
。
DownloadString
and UploadString
, as all WebClient
方法,也适用于 ftp://
URLs:
By default, the .NET Framework supports URIs that begin with
http:
,https:
,ftp:
, andfile:
scheme identifiers.
因此,除非您需要一些花哨的选项,否则它很简单:
$webclient = New-Object System.Net.WebClient
$contents = $webclient.DownloadString("ftp://ftp.example.com/file.txt")
如果您需要向 FTP 服务器进行身份验证,请将凭据添加到 URL:
ftp://username:password@ftp.example.com/file.txt
$webclient = New-Object System.Net.WebClient
$webclient.Credentials = New-Object System.Net.NetworkCredential("user", "mypassword")
$contents = $webclient.DownloadString("ftp://ftp.example.com/file.txt")