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 脚本


- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 输入按键事件处理程序 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01