Search code examples
powershellwinscpwinscp-net

Download files from last 3 days using WinSCP .NET assembly in PowerShell


I have this script and I want to collect all file with extension *.did for the last 3 days but it fails with below error.

I don't think that I use correctly the Get-ChildItem.

Thanks for your help

$session = New-Object WinSCP.Session

$file = "*.did"
$localPath = "E:\logs\Log\Arhive\*" 
$remotePath = Get-ChildItem "/C:/logs/*.did" | where{$_.LastWriteTime -le (GetDate).AddDays(-3)}

try {
    # Connect
    $session.Open($sessionOptions)

    # Check exists files
    foreach ($remotePath in $remotePath)
    {
        if ($session.FileExists($remotePath))
        {
            Write-Host "[OK] Log $remotePath exist" -ForegroundColor Green
            # Transfer files

            $session.GetFiles($remotePath, $localPath).Check()
        }
        else
        {
            Write-Host "[X] Log $remotePath NO exist" -ForegroundColor Red
        }
    }
}
finally {
    $session.Dispose()
}

foreach ($file in "E:\logs\Log\Arhive\*.did") {
    if (Test-Path $file) {
        Compress-Archive $file -DestinationPath "E:\logs\Log\Arhive\$inputID.zip" -Update
        Remove-Item $file
    }
}
(Get-ChildItem : Cannot find drive. A drive with the name '/C' does not exist.
At C:\Users\me\Desktop\collectLog.ps1:167 char:15
+ ... emotePath = Get-ChildItem "/C:/logs/*.d ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (/C:String) [Get-ChildItem], DriveNotFoundException
    + FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand

Solution

  • You cannot use Get-ChildItem with remote files.

    You would need to use Session.ListDirectory.
    Like here: Using WinSCP from PowerShell to retrieve files modified within the last hour


    But actually, WinSCP can do this for you easily using a file mask with a time constraint:

    $localPath = "E:\logs\Log\Arhive" 
    $remotePath = "/C:/logs"
    $session.GetFilesToDirectory($remotePath, $localPath, "*.did>=3D").Check()