首页 > 解决方案 > 将字符串添加到位于 FTP 服务器上的现有文本文件

问题描述

我想将此添加到我的代码中:

$path="ftp://localhost/file1.txt"
$y="yes"
ADD-content -path $path -value  $a   

请问有什么好的方法吗?我们假设 $LocalFile 不存在。我只想在我的远程 ftp 文件 $RemoteFile file1.txt 中添加一个值 $y="yes"

# Config
$Username = "username"
$Password = "password"
$LocalFile = "C:\test100\log1.txt"
$RemoteFile = "ftp://localhost/file1.txt"
 
# Create FTP Rquest Object
$FTPRequest = [System.Net.FtpWebRequest]::Create("$RemoteFile")
$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 = [System.IO.File]::ReadAllBytes($LocalFile)
$FTPRequest.ContentLength = $FileContent.Length
# Get Stream Request by bytes
$Run = $FTPRequest.GetRequestStream()
$Run.Write($FileContent, 0, $FileContent.Length)
# Cleanup
$Run.Close()
$Run.Dispose()

标签: powershell

解决方案


您想使用位于本地磁盘上的另一个文件内容来“更新”位于 FTP 服务器上的文件内容。

尝试这个 :

# Your Local File
$File = "C:/log.txt"

# Your FTP Server location
$FTP = "ftp://root:root@localhost/test.txt"

# Create a Web Client
$Web_Client   = New-Object System.Net.WebClient

# Set file URI from your FTP Server
$URI          = New-Object System.Uri($FTP)

# Get Local File Content
$File_Content = Get-Content $File

# Download content of the file
$New_Content  = $Web_Client.DownloadString($URI)

# Add Local File Content to the downloaded content previously
$New_Content  = $New_Content + $File_Content

# Upload the Whole Content (Old + New Line)
$Web_Client.UploadString($URI,$New_Content)

# Free the Web  Client
$Web_Client.Dispose()

推荐阅读