如何直接将PowerShell变量内容上传至FTP服务器(无需本地文件)
无本地文件直接将PowerShell变量内容上传至FTP服务器
方法1:使用内置.NET FtpWebRequest 类(兼容所有PowerShell版本)
这是最通用的方案,无需额外安装模块,直接从内存将字符串/字节数据写入FTP流:
# 示例变量(多行内容) $cm = tasklist | Out-String $session_token = "your_session_token_here" # FTP服务器配置 $ftpServerPath = "ftp://your-ftp-server.com/upload/tasklist.txt" $ftpUsername = "your-ftp-username" $ftpPassword = "your-ftp-password" # 将字符串转换为字节数组(根据内容编码调整,如UTF-8/GB2312) $contentBytes = [System.Text.Encoding]::UTF8.GetBytes($cm) # 创建FTP上传请求 $ftpRequest = [System.Net.FtpWebRequest]::Create($ftpServerPath) $ftpRequest.Method = [System.Net.WebRequestMethods+Ftp]::UploadFile $ftpRequest.Credentials = New-Object System.Net.NetworkCredential($ftpUsername, $ftpPassword) $ftpRequest.UseBinary = $false # 文本内容用ASCII模式,二进制文件设为$true $ftpRequest.UsePassive = $true # 多数FTP服务器需启用被动模式 # 写入内存数据到FTP流 $requestStream = $ftpRequest.GetRequestStream() $requestStream.Write($contentBytes, 0, $contentBytes.Length) $requestStream.Close() # 验证上传结果 $ftpResponse = $ftpRequest.GetResponse() Write-Host "上传状态: $($ftpResponse.StatusDescription)" $ftpResponse.Close()
方法2:使用 Invoke-WebRequest(PowerShell 5.1+ 可用)
语法更简洁,适合快速实现:
$cm = tasklist | Out-String $ftpServerPath = "ftp://your-ftp-server.com/upload/tasklist.txt" $ftpCreds = New-Object System.Net.NetworkCredential("username", "password") # 将字符串转为字节数组,直接通过Body参数上传 $contentBytes = [System.Text.Encoding]::UTF8.GetBytes($cm) Invoke-WebRequest -Uri $ftpServerPath -Method Put -Body $contentBytes -Credential $ftpCreds
封装为定时上传脚本(每10秒执行)
将上传逻辑封装为函数,配合循环实现定时任务,全程无本地文件生成:
function Upload-ToFtp { param( [string]$Content, [string]$FtpPath, [System.Net.NetworkCredential]$Credentials ) try { $contentBytes = [System.Text.Encoding]::UTF8.GetBytes($Content) $ftpRequest = [System.Net.FtpWebRequest]::Create($FtpPath) $ftpRequest.Method = [System.Net.WebRequestMethods+Ftp]::UploadFile $ftpRequest.Credentials = $Credentials $ftpRequest.UseBinary = $false $ftpRequest.UsePassive = $true $requestStream = $ftpRequest.GetRequestStream() $requestStream.Write($contentBytes, 0, $contentBytes.Length) $requestStream.Close() $response = $ftpRequest.GetResponse() Write-Host "[$(Get-Date)] 上传完成: $($response.StatusDescription)" $response.Close() } catch { Write-Error "[$(Get-Date)] 上传失败: $_" } } # 初始化配置 $ftpCreds = New-Object System.Net.NetworkCredential("username", "password") $ftpTargetPath = "ftp://your-ftp-server.com/upload/tasklist.txt" # 每10秒执行一次上传 while($true) { $cm = tasklist | Out-String Upload-ToFtp -Content $cm -FtpPath $ftpTargetPath -Credentials $ftpCreds Start-Sleep -Seconds 10 }
注意事项
- 编码适配:如果内容包含中文或特殊字符,替换编码为对应格式,例如
[System.Text.Encoding]::GetEncoding("GB2312")。 - 被动模式:若连接失败,尝试将
UsePassive设为$false(取决于FTP服务器配置)。 - 权限验证:确保FTP用户拥有目标路径的写入权限。
内容的提问来源于stack exchange,提问作者ValB
相关产品推荐
相关产品推荐

