Post a reply

Options
Add an Attachment

If you do not want to add an Attachment to your Post, please leave the Fields blank.

(maximum 10 MB; please compress large files; only common media, archive, text and programming file formats are allowed)

Options

Topic review

traveller198

Re: PowerShell script failing

This did the trick, thank you!
traveller198

PowerShell script failing

Hi All,

I have the following script to upload the newest file from a number of subfolders. The script lists the files to upload but then fails to upload them with the error:

Uploading "Filename of first file" ...
Error: Exception calling "Check" with "0" argument(s): "File or Folder 'Filename of first file' does not exist.
System error. Code: 2.
The system cannot find the file specified"

Script:
try
{
    # Load WinSCP .NET assembly
    Add-Type -Path "WinSCPnet.dll"
 
    # Setup session options
    $sessionOptions = New-Object WinSCP.SessionOptions -Property @{
        Protocol = [WinSCP.Protocol]::Sftp
        HostName = "FQDN of host"
        UserName = "USER"
        Password = "PASS"
        SshHostKeyFingerprint = "FINGERPRINT"
    }
 
    $session = New-Object WinSCP.Session
 
    try
    {
        # Connect
        $session.Open($sessionOptions)
 
        $remotePath = "REMOTE PATH"
 
        $lines = Get-ChildItem -Path I:\path\to\toplevelfolder -Recurse -File -Filter *.bak | group directory | foreach {$_.group | sort LastWriteTime -Descending | select -First 1}
 
        foreach ($line in $lines)
        {
            Write-Host "Uploading $line ..."
            $session.PutFiles($line, $remotePath).Check()
        }
    }
    finally
    {
        # Disconnect, clean up
        $session.Dispose()
    }
 
    exit 0
}
catch
{
    Write-Host "Error: $($_.Exception.Message)"
    exit 1
}

Could any one provide advise as to why the error is returned and the selected files are not uploaded? $lines does seem to provide the correct files for upload so not sure where I have gone wrong here.