問題描述
我正在使用 PowerShell 腳本將整個(gè)文件夾的內(nèi)容上傳到 FTP 位置.我對(duì) PowerShell 很陌生,只有一兩個(gè)小時(shí)的經(jīng)驗(yàn).我可以很好地上傳一個(gè)文件,但找不到一個(gè)好的解決方案來處理文件夾中的所有文件.我假設(shè)一個(gè) foreach
循環(huán),但也許有更好的選擇?
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()
推薦答案
循環(huán)(甚至更好的遞歸)是在 PowerShell(或一般的 .NET)中本地執(zhí)行此操作的唯一方法.
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()
請(qǐng)注意,上面的代碼不會(huì)遞歸到子目錄中.
Note that the above code does not recurse into subdirectories.
如果您需要更簡(jiǎn)單的解決方案,則必須使用 3rd 方庫(kù).
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()
上面的代碼確實(shí)是遞歸的.
The above code does recurse.
請(qǐng)參閱 https://winscp.net/eng/docs/library_session_putfiles
(我是 WinSCP 的作者)
這篇關(guān)于將整個(gè)文件夾上傳到 FTP 的 PowerShell 腳本的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!