PowerShell Script Not Working
I am trying to use the below script to upload files with SFTP but it is not working. The script executes and returns to a prompt, but my file never uploads. Can someone please take a look and see if they see something I am missing? I can add the credentials manually to the GUI and everything works correctly.
param (
$localPath = "XXXXXXXXX",
$remotePath = "XXXXXXXXXXX",
$backupPath = "XXXXXXXXXXX"
)
try
{
# Load WinSCP .NET assembly
Add-Type -Path "c:\progra~2\winscp\WinSCPnet.dll"
# Load WinSCP .NET assembly
#[Reflection.Assembly]::LoadFrom("WinSCP.dll") | Out-Null
# Connection Settings
$sessionOptions = New-Object WinSCP.SessionOptions
$sessionOptions.Protocol = [WinSCP.Protocol]::Sftp
$sessionOptions.HostName = "XXXXXXXXXXX"
$sessionOptions.UserName = "XXXXXXXXXXX"
$sessionOptions.Password = "XXXXXXXXXXX"
$sessionOptions.GiveUpSecurityAndAcceptAnySshHostKey = "true"
#$sessionOptions.SshHostKeyFingerprint =
$session = New-Object WinSCP.Session
try
{
# Connect
$session.Open($sessionOptions)
# Upload files, collect results
$transferResult = $session.PutFiles($localPath, $remotePath)
# Iterate over every transfer
foreach ($transfer in $transferResult.Transfers)
{
# Success or error?
if ($transfer.Error -eq $Null)
{
Write-Host ("Upload of {0} succeeded, moving to backup" -f
$transfer.FileName)
# Upload succeeded, move source file to backup
Move-Item $transfer.FileName $backupPath
}
else
{
Write-Host ("Upload of {0} failed: {1}" -f
$transfer.FileName, $transfer.Error.Message)
}
}
}
finally
{
# Disconnect, clean up
$session.Dispose()
}
exit 0
}
catch [Exception]
{
Write-Host $_.Exception.Message
exit 1
}
param (
$localPath = "XXXXXXXXX",
$remotePath = "XXXXXXXXXXX",
$backupPath = "XXXXXXXXXXX"
)
try
{
# Load WinSCP .NET assembly
Add-Type -Path "c:\progra~2\winscp\WinSCPnet.dll"
# Load WinSCP .NET assembly
#[Reflection.Assembly]::LoadFrom("WinSCP.dll") | Out-Null
# Connection Settings
$sessionOptions = New-Object WinSCP.SessionOptions
$sessionOptions.Protocol = [WinSCP.Protocol]::Sftp
$sessionOptions.HostName = "XXXXXXXXXXX"
$sessionOptions.UserName = "XXXXXXXXXXX"
$sessionOptions.Password = "XXXXXXXXXXX"
$sessionOptions.GiveUpSecurityAndAcceptAnySshHostKey = "true"
#$sessionOptions.SshHostKeyFingerprint =
$session = New-Object WinSCP.Session
try
{
# Connect
$session.Open($sessionOptions)
# Upload files, collect results
$transferResult = $session.PutFiles($localPath, $remotePath)
# Iterate over every transfer
foreach ($transfer in $transferResult.Transfers)
{
# Success or error?
if ($transfer.Error -eq $Null)
{
Write-Host ("Upload of {0} succeeded, moving to backup" -f
$transfer.FileName)
# Upload succeeded, move source file to backup
Move-Item $transfer.FileName $backupPath
}
else
{
Write-Host ("Upload of {0} failed: {1}" -f
$transfer.FileName, $transfer.Error.Message)
}
}
}
finally
{
# Disconnect, clean up
$session.Dispose()
}
exit 0
}
catch [Exception]
{
Write-Host $_.Exception.Message
exit 1
}