使用Powershell通过sftp协议将多个本地文件夹及其内容移动到远程服务器

时间:2018-09-27 07:59:05

标签: powershell sftp winscp

我想将特定文件从本地目录移动到远程服务器的文件夹。

文件在主目录内的文件夹中生成。 文件夹的名称是实际的日期,并且其中包含文件。 在某些情况下,文件名相同,但它们位于单独的文件夹中。 例如:

\main\
     \201809271020\a20180927.txt
     \201809271120\a20180927.txt
     \201809271220\a20180927.txt

我必须将主文件夹下的所有文件夹和文件移动到远程位置。 我已经尝试过使用WinSCP powershell模块,但是它仅适用于文件。我无法移动文件夹。 任何帮助表示赞赏。

致谢

wolfnlight

1 个答案:

答案 0 :(得分:0)

好吧,我创建了一个脚本,希望它不会那么糟糕。 :)

[xml]$config = Get-Content "C:\Script\config.xml" -ErrorAction Stop
[string]$serverName = $config.Configuration.HostName
[string]$UserName = $config.Configuration.UserName
[string]$localPath = $config.Configuration.LocalPath
[string]$remotePath = $config.Configuration.RemotePath
[string]$logFile =  $config.Configuration.LogFile
[string]$SshHostKeyFingerprint = $config.Configuration.SshHostKeyFingerprint
[string]$SshPrivateKeyPath = $config.Configuration.SshPrivateKeyPath
[string]$wildcard = $config.Configuration.WildCard

Import-Module -Name "C:\Program Files (x86)\WindowsPowerShell\Modules\WinSCP" -Force

############# functions for log ##########################################
function InfoToLog {
return "$(get-date -Format "yyyy.MM.dd HH:mm:ss") - [INFO] - "
}

function WarningToLog {
return "$(get-date -Format "yyyy.MM.dd HH:mm:ss") - [WARNING] - "
}

function ErrorToLog {
return "$(get-date -Format "yyyy.MM.dd HH:mm:ss") - [ERROR] - "
}

############ Uploader ####################################################

function Data-Uploader {

param (
    $i = 0
)

    foreach ($localFile in $localFiles) {

        $localDirName = $localFiles[$i].FullName.Substring(38,15)
        $localDir = $localPath + $localDirName
        $remoteDir = $remotePath + $localDirName
        $GetLocalDir = Get-ChildItem -Path $localDir -Recurse -Include "export.end" -ErrorAction Stop  

        if (($GetLocalDir)) {

                    # target directory query 
                    if (!(Test-WinSCPPath $session -Path $remoteDir)) {

                        $(InfoToLog) +  $remoteDir + " not exist...creating"  | Out-File $logFile -Append

                            New-WinSCPItem -WinSCPSession $session -Path $remoteDir -ItemType "directory" -Verbose -ErrorAction Stop

                        $(InfoToLog) +  $remoteDir + " created"  | Out-File $logFile -Append
                    }
                    else {
                        $(InfoToLog) +  $remoteDir + " exists!"  | Out-File $logFile -Append
                    }

                $localFileName = $localFiles[$i].FullName
                $remotefileName = $localFiles[$i].Name

                    # put files from local directory to remote directory - same name
                    if ($localFileName -like "*$localDir*") {

                        $localFile = "FileName: " + $localFile.Name + " - CreationTime: " + $localFile.CreationTime.GetDateTimeFormats('u') + "- Length(kB): " + $localFile.Length 

                        $(InfoToLog) +  $localFile | Out-File $logFile -Append

                        $(InfoToLog) + "Transfering $remotefileName ..."  | Out-File $logFile -Append

                            Send-WinSCPItem -TransferOptions $TransferOptions `
                                            -WinSCPSession $session `
                                            -LocalPath "$localDir\$wildcard" `
                                            -RemotePath $remoteDir -ErrorAction Stop -Verbose

                        $(InfoToLog) + "$remotefileName transfered."  | Out-File $logFile -Append

                        $(InfoToLog) + "Archiving files..."  | Out-File $logFile -Append

                            Move-Item -Path $localDir -Destination "C:\Script\Archive\" -Force -ErrorAction Stop -Verbose 

                        $(InfoToLog) + "Archiving completed."  | Out-File $logFile -Append

                    }
                    else { 
                        $(InfoToLog) + "No file for transfer."  | Out-File $logFile -Append
                    }
            }
            else { 
                $(WarningToLog) + "$localFile - waiting for export ended!"  | Out-File $logFile -Append
            }
        $i++
        }
}
################# process ######################################
try {

$(InfoToLog) + "Data_Uploader - version 1.2 - Starting script..." | Out-File $logFile -Append

# set user
$MyCredential = New-Object System.Management.Automation.PSCredential ($UserName, (new-object System.Security.SecureString))

# set session
$sessionOption = New-WinSCPSessionOption -Credential $MyCredential -HostName $serverName -Protocol sftp -SshHostKeyFingerprint $SshHostKeyFingerprint -SshPrivateKeyPath $SshPrivateKeyPath
$TransferOptions = New-WinSCPTransferOption -FileMask $wildcard -TransferMode Binary 

# connecting
$session = New-WinSCPSession -SessionOption $sessionOption -ErrorAction Stop -SessionLogPath "C:\Script\MUK\Log\Muk_Uploader_session.log"

    # session available
    if ($session.Opened -eq $true) {

        $(InfoToLog) + "Connected to $servername..." | Out-File $logFile -Append

        # get local files
        $localFiles = Get-ChildItem -Path $localPath -Recurse -ErrorAction Stop -Verbose -Attributes !Directory -Exclude "riport.end"

            # existing files in local dir
            if ($localFiles.Count -gt 0) {

                $(InfoToLog) + $localFiles.Count +" files in $localPath :" | Out-File $logFile -Append

                # upload files
                Data-Uploader 
            }                
            else {

                $(InfoToLog) + "No files in $localPath" | Out-File $logFile -Append
            }

    } 
    else {

        $(ErrorToLog) + "$($_.Exception.Message)" | Out-File $logFile -Append

        } 
} # try

catch {
Write-Host -ForegroundColor Green "Error: $($_.Exception.Message)"

$(ErrorToLog) + "Message: $($_.Exception.Message)" | Out-File $logFile -Append

# session close
Remove-WinSCPSession -WinSCPSession $session -ErrorAction Stop
}
finally {

$(InfoToLog) + "End script!" | Out-File $logFile -Append 
"$(get-date -Format "yyyy.MM.dd HH:mm:ss") - ***************************************************************************************************" | Out-File $logFile -Append 

# session close 
Remove-WinSCPSession -WinSCPSession $session -ErrorAction Stop
}

有什么建议吗?