将整个文件夹上传到 FTP 的 PowerShell 脚本

PowerShell Script to upload an entire folder to FTP(将整个文件夹上传到 FTP 的 PowerShell 脚本)
本文介绍了将整个文件夹上传到 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 脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
quot;Overflowquot; compiler error with -9223372036854775808L(编译器错误-9223372036854775808L(Q;溢出Q))
Visual Studio 2010 ReportViewer Assembly References(Visual Studio 2010 ReportViewer程序集引用)
Weird behaviour when I open a reportviewer in WPF(在WPF中打开报表查看器时出现奇怪的行为)
how do i pass parameters to aspnet reportviewer(如何将参数传递给aspnet report查看器)