try
{
# Carga del ensamblado .NET para WinSCP
Add-Type -Path "C:\tmp\smeg\winscp\WinSCPnet.dll"
# Configuración de opciones de sesión
$sessionOptions = New-Object WinSCP.SessionOptions -Property @{
Protocol = [WinSCP.Protocol]::Sftp
HostName = "127.0.0.1"
PortNumber = 22
UserName = "user1"
Password = "user1"
SshHostKeyFingerprint = "ssh-rsa"
}
# Configuración de caminos local y remoto
$remotePath = "/"
$LocalPath = "d:\XPO\data\*.csv"
$BackUPPath = "d:\XPO\sent\"
$LogFile = "d:\XPO\log\GPoutput.csv"
# Configuración de opciones Conexión
$sessionOptions.AddRawSettings("FSProtocol", "2")
$session = New-Object WinSCP.Session
try
{
# Conexión
$session.Open($sessionOptions)
# Opciones de configuración de transferencia
$session.add_QueryReceived( {
#Write-Host "Error: $($_.Message)"
$_.Continue()
} )
$transferOptions = New-Object WinSCP.TransferOptions -Property @{
PreserveTimestamp = $False
}
$transferOptions.TransferMode = [WinSCP.TransferMode]::Binary
#$transferOptions.AddRawSettings("IgnorePermErrors", "1")
$transferOptions.AddRawSettings("ExcludeHiddenFiles", "1")
$Item = $Null
# Envio de archivos hacia el host remoto
foreach( $Item in Get-ChildItem $LocalPath )
{
$NewName = "SMEG_Alvaranes " + (Get-Date -Format "yyyy-MM-dd HHmmss") + ".csv"
rename-item $Item -NewName $NewName
Start-Sleep -Seconds 1
}
# Envio de archivos hacia el host remoto
foreach( $Item in Get-ChildItem $LocalPath )
{
$TransferResult =
$session.PutFiles( $Item, $remotePath, $false, $transferOptions)#.Check()
# Throw on any error
$transferResult.Check()
write-host $transferResult.IsSuccess
#Crear Carpeta de Backup
$st1 = $BackUPPath
$st2 = Get-Date -Format "yyyy"
$st3 = "\"
$st4 = Get-Date -Format "MM"
$Backup = [System.String]::Concat($st1, $st2, $st3, $st4)
$ExBk= Test-Path $Backup
if ($ExBk -ne $True)
{
mkdir $Backup
}
#Comprobar si se ha realizado la copia correctamente
if (!$transferResult.IsSuccess )
{
Write-Host $Item.name + $transferResult.IsSuccess + "Error"
}
else
{
Write-Host $Item.name + $transferResult.IsSuccess + "Success"
Move-Item $Item $Backup
}
#Output the array to the CSV File
$Output =New-Object -TypeName PSObject -Property @{
File = $Item.name
Date = Get-Date -Format "yyyy/MM/dd"
Hour = Get-Date -Format "HH:mm:ss"
Result = $transferResult.IsSuccess
Host = $sessionOptions.HostName
Path = $remotePath
UserName = $sessionOptions.UserName
} | Select-Object Date,Hour,File,Result,Host,Username, Path,Error
$Output | Export-Csv $LogFile -NoTypeInformation -Append
}
}
finally
{
# Disconnect, clean up
$session.Dispose()
}
exit 0
}
catch
{
#Muestra Errores
Write-Host "Error: $($_.Exception.Message)"
if ($Null -ne $($_.Exception.Message)) {
#Registra Errores en el Log
$Output =New-Object -TypeName PSObject -Property @{
Date = Get-Date -Format "yyyy/MM/dd"
Hour = Get-Date -Format "HH:mm:ss"
Error = $($_.Exception.Message)
} | Select-Object Date,Hour,File,Result,Error
$Output | Export-Csv $LogFile -NoTypeInformation -Append
}
exit 1
}