【问题标题】:PowerShell Script to upload an entire folder to FTP将整个文件夹上传到 FTP 的 PowerShell 脚本
【发布时间】:2015-10-25 19:28:58
【问题描述】:

我正在使用 PowerShell 脚本将整个文件夹的内容上传到 FTP 位置。我对 PowerShell 很陌生,只有一两个小时的经验。我可以很好地上传一个文件,但找不到一个好的解决方案来处理文件夹中的所有文件。我假设一个foreach 循环,但也许有更好的选择?

$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()

【问题讨论】:

    标签: .net powershell ftp webclient


    【解决方案1】:

    循环(甚至更好的递归)是在 PowerShell(或一般的 .NET)中本机执行此操作的唯一方法。

    $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()
    

    请注意,上面的代码不会递归到子目录中。


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

    例如WinSCP .NET assembly:

    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()
    

    上面的代码确实是递归的。

    https://winscp.net/eng/docs/library_session_putfiles

    (我是 WinSCP 的作者)

    【讨论】:

    • 非常感谢,这太棒了。我下载了winscp,来看看。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-05
    • 1970-01-01
    • 2012-07-06
    • 1970-01-01
    • 2014-05-15
    相关资源
    最近更新 更多