PowerShell Script to upload an entire folder to FTP(将整个文件夹上传到 FTP 的 PowerShell 脚本)
问题描述
我正在使用 PowerShell 脚本将整个文件夹的内容上传到 FTP 位置.我对 PowerShell 很陌生,只有一两个小时的经验.我可以很好地上传一个文件,但找不到一个好的解决方案来处理文件夹中的所有文件.我假设一个 foreach
循环,但也许有更好的选择?
I'm working on a PowerShell script to upload the contents of an entire folder to an FTP location. I'm pretty new to PowerShell with only an hour or two of experience. I can get one file to upload fine but can't find a good solution to do it for all files in the folder. I'm assuming a foreach
loop, but maybe there's a better option?
$source = "c: est"
$destination = "ftp://localhost:21/New Directory/"
$username = "test"
$password = "test"
# $cred = Get-Credential
$wc = New-Object System.Net.WebClient
$wc.Credentials = New-Object System.Net.NetworkCredential($username, $password)
$files = get-childitem $source -recurse -force
foreach ($file in $files)
{
$localfile = $file.fullname
# ??????????
}
$wc.UploadFile($destination, $source)
$wc.Dispose()
推荐答案
循环(甚至更好的递归)是在 PowerShell(或一般的 .NET)中本地执行此操作的唯一方法.
The loop (or even better a recursion) is the only way to do this natively in PowerShell (or .NET in general).
$source = "c:source"
$destination = "ftp://username:password@example.com/destination"
$webclient = New-Object -TypeName System.Net.WebClient
$files = Get-ChildItem $source
foreach ($file in $files)
{
Write-Host "Uploading $file"
$webclient.UploadFile("$destination/$file", $file.FullName)
}
$webclient.Dispose()
请注意,上面的代码不会递归到子目录中.
Note that the above code does not recurse into subdirectories.
如果您需要更简单的解决方案,则必须使用 3rd 方库.
If you need a simpler solution, you have to use a 3rd party library.
例如使用 WinSCP .NET 程序集:
Add-Type -Path "WinSCPnet.dll"
$sessionOptions = New-Object WinSCP.SessionOptions
$sessionOptions.ParseUrl("ftp://username:password@example.com/")
$session = New-Object WinSCP.Session
$session.Open($sessionOptions)
$session.PutFiles("c:source*", "/destination/").Check()
$session.Dispose()
上面的代码确实是递归的.
The above code does recurse.
请参阅 https://winscp.net/eng/docs/library_session_putfiles
(我是 WinSCP 的作者)
这篇关于将整个文件夹上传到 FTP 的 PowerShell 脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将整个文件夹上传到 FTP 的 PowerShell 脚本
基础教程推荐
- MS Visual Studio .NET 的替代品 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- c# Math.Sqrt 实现 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01