2

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!

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992

2 Answers2

2

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"
}
Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
0

I finally modified the script from Martin and now it cans successfully check if there are less or more than 4 files in my directory:

$remotePath = "/my-directory"

$files = $session.ListDirectory($remotePath).Files | Where-Object { -Not $_.IsDirectory }

$count = $files.Count

if ($count -le 4)
{
   Write-Host "There are less than 4 files into the"$remotePath" directory. All good!"
}
else
{
    Write-Host "There are more than 4 files into the"$remotePath" directory. Please check!"
}

I actually needed the .Files argument after $session.ListDirectory.

Thanks!

  • 1
    Ok, you are right about the missing `.Files`. I've corrected that in my answer. Though now your answer is bit redundant :) – Martin Prikryl Aug 10 '21 at 10:35