Search code examples
powershellsftpwinscpwinscp-net

PowerShell and WinSCP script to check if there are more than 4 files in a SFTP remote directory


With PowerShell language and WinSCP I'm trying to create a script that daily check an SFTP remote directory to see if there are more than 4 files into it.

If there are less than 4 files it's okay but if there are more that 4 files it will output an error message.

Thanks to WinSCP, the connexion is automatically created and I can below connect into the SFTP-Server:

& "C:\Program Files (x86)\WinSCP\WinSCP.com"
  /log="C:\Users\scripts\WinSCP.log" /ini=nul
  /command
    "open sftp://..."
    "cd" `
    "cd ./my remote directory"
    #"ls *.csv"
    #"exit"

$winscpResult = $LastExitCode
if ($winscpResult -eq 0)
{
  Write-Host "Success"
}
else
{
  Write-Host "Error"
}

exit $winscpResult

I don't know if I have to do this through script or .NET assembly language:

# Load WinSCP .NET assembly
Add-Type -Path "WinSCPnet.dll"

# Set up session options
$sessionOptions = New-Object WinSCP.SessionOptions -Property @{
    Protocol = [WinSCP.Protocol]::Sftp
    HostName = ""
    UserName = ""
    Password = ""
    SshHostKeyFingerprint = ""
    TimeoutInMilliseconds = 60000
}

$session = New-Object WinSCP.Session

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

    # Your code
}
finally
{
    $session.Dispose()
}

I however currently don't know how to perform the condition.

When the script is done the goal would be to use it into Jenkins to run it daily.

Could you help me to build the check condition with and else? Thanks!


Solution

  • With the WinSCP .NET assembly, it's trivial:

    $files =
        $session.ListDirectory($remotePath).Files |
            Where-Object { -Not $_.IsDirectory }
    $count = $files.Count
    if ($count -gt 4)
    {
        Write-Host "There are more than 4 files in $remotePath"
    }