Set-SFTPFile上传全目录



我需要通过sftp上传完整目录(包含可检索文件夹)到服务器

#SSH
$secpasswd = ConvertTo-SecureString $Password -AsPlainText -Force
$Credentials = New-Object System.Management.Automation.PSCredential($User, $secpasswd)
$sftpSession = New-SFTPSession -ComputerName $HostIP -Credential $Credentials
#Folders Paths
$FilePath = Get-ChildItem -Path uploading-folder | Select-Object -ExpandProperty FullName
$SftpPath = "/home/new-folder"
# Upload the file to the SFTP path
Set-SFTPFile -SessionId ($sftpSession).SessionId -LocalFile $FilePath -RemotePath $SftpPath -Overwrite
#Disconnect all SFTP Sessions
Get-SFTPSession | % { Remove-SFTPSession -SessionId ($_.SessionId) }

但是我不能在文件夹中上传文件夹(并在其中上传文件)。如何上传包含文件和文件夹的完整文件夹?

Posh似乎不支持递归操作。你必须自己编码。

引用Reddit post SFTP -如何上传整个文件夹/目录而不是一次一个文件?:

# Get a recursive list of files in the target folder ($path).  
# Change the include to your needs,
# and remove the -Force if you don't want hidden files included
$path = "./Recursion test/"
$uploadFiles = Get-ChildItem $path -Recurse -Include "*" -Force
$session = New-SFTPSession (your args here)
$remoteFolder = Get-SFTPCurrentDirectory $sessoin.Index
Set-SFTPDirectoryPath $session.Index -Path $destinationPath
foreach ($item in $uploadFiles) {
if ($item.GetType -eq [System.IO.DirectoryInfo]) {
New-SFTPDirectory $sessionIndex $item
}
else {
$localFolder = $item.PSPath | Split-Path | Split-Path -Leaf
if ($localFolder -ne $remoteFolder) {
Set-SFTPCurrentDirectory $session.Index $localFolder
$remoteFolder = $localFolder
}
Set-SFTPFile $session.Index $item.Name
}
}

或者使用其他支持递归操作的SFTP库

代码:

$folders =  @('D:Sharesfolderone*.pdf','D:Sharesfoldertwo*.pdf')
foreach ($folder in $folders) {
$files = Get-ChildItem $folder
foreach ($file in $files) {
Set-SFTPItem -SessionId $SFTPSession.SessionId -Path $file -Destination /upload -Verbose
}
}

相关内容

  • 没有找到相关文章

最新更新