-1

I want to move specific files from a local directory to a folder of a remote server.

The files are generated in folders inside the main directory. The names of the folders are the actual dates and inside them there are files. In some cases the names of the files are the same but they are in separate folders. For example:

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

I have to move all of the folders and files under the main folder to the remote location. I've tried it with WinSCP powershell module, but it works on files only. I couldn't move folders with it. Any helps appreciated.

Regards

wolfnlight

henrycarteruk
  • 12,708
  • 2
  • 36
  • 40
wolfnlight
  • 23
  • 1
  • 4

1 Answers1

0

Ok, I create a script, I hope it will not so bad. :)

[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
}

Any suggestions?

wolfnlight
  • 23
  • 1
  • 4