如何使用 PowerShell 上傳文件至 FTP

  1. 使用 System.Net.WebClient 物件透過 FTP 在 PowerShell 中上傳檔案
  2. 使用 FtpWebRequest 物件透過 FTP 在 PowerShell 中上傳檔案
  3. 使用 FTP 在 PowerShell 中上傳多個檔案
如何使用 PowerShell 上傳文件至 FTP

FTP(檔案傳輸協定)是一種標準網路協定,用於在計算機網路上的客戶端和伺服器之間傳輸檔案。FTP 伺服器是一個常見的解決方案,以便於在互聯網上傳輸檔案。

我們可以將檔案上傳到 FTP 伺服器,也可以從 FTP 伺服器下載檔案。PowerShell 是一個可以自動化 FTP 上傳和下載任務的腳本工具。

本教程將教您如何使用 PowerShell 將檔案上傳到 FTP 伺服器。

使用 System.Net.WebClient 物件透過 FTP 在 PowerShell 中上傳檔案

我們可以使用 System.Net.WebClient 物件將檔案上傳到 FTP 伺服器。它可以從任何由 URI 標識的本地、內部網路或網際網路資源發送或接收數據。

首先,我們需要創建一個 System.Net.WebClient 物件的實例並將其賦值給變數 $WebClientNew-Object Cmdlet 創建 .NET Framework 或 COM 物件的實例。

$WebClient = New-Object System.Net.WebClient

現在,讓我們指定一個檔案和 FTP URI。使用有效的用戶名和密碼來訪問伺服器。因此,用您的 FTP 資訊替換 $FTP 中的值。

$File = "C:\New\car.png"
$FTP = "ftp://ftp_user:ftp_password@ftp_host/car.png"

然後創建一個 FtpWebRequest 物件並按如下所示配置它。Credentials 屬性用於指定連接到 FTP 伺服器的憑證。

UseBinary 屬性設置布林值來指定檔案傳輸的數據類型。True 表示要傳輸的數據為 binary,而 false 表示要傳輸的數據為 text

此方法使用二進制傳輸模式來傳輸檔案,無需進行修改或轉換。因此,源計算機上的相同檔案將上傳到伺服器。

$FTPRequest = [System.Net.FtpWebRequest]::Create("$remote_file")
$FTPRequest = [System.Net.FtpWebRequest]$FTPRequest
$FTPRequest.Method = [System.Net.WebRequestMethods+Ftp]::UploadFile
$FTPRequest.Credentials = New-Object System.Net.NetworkCredential($username, $password)
$FTPRequest.UseBinary = $true
$FTPRequest.UsePassive = $true

# Read the file for upload
$FileContent = gc -en byte $local_file
$FTPRequest.ContentLength = $FileContent.Length

# Get stream request by bytes
$run = $FTPRequest.GetRequestStream()
$run.Write($FileContent, 0, $FileContent.Length)

# Cleanup
$run.Close()
$run.Dispose()

當使用 FtpWebRequest 物件上傳檔案到伺服器時,我們必須將檔案內容寫入通過調用 GetRequestStream 方法獲得的請求流。

我們必須先寫入流並關閉它,然後才能發送請求。

使用 FTP 在 PowerShell 中上傳多個檔案

有時,我們可能需要一次性將多個檔案上傳到 FTP 伺服器。逐個上傳檔案會耗費大量時間。

因此,我們創建了此 PowerShell 腳本,以一次性將多個檔案上傳到 FTP 伺服器。

首先,創建一個 System.Net.WebClient 物件並將其賦值給變數 $WebClient

$WebClient = New-Object System.Net.WebClient

指定要上傳的所有檔案所在的目錄。

$Dir = "C:\New"

然後指定您的 FTP 伺服器的 URI。

$FTP = "ftp://ftp_user:ftp_password@ftp_host/docs/"