将整个文件夹上传到FTP的PowerShell脚本 [英] PowerShell Script to upload an entire folder to FTP

查看:661
本文介绍了将整个文件夹上传到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:\test"
$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.

如果您需要更简单的解决方案,则必须使用第三方库。

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脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆