0

I'm new to using the PowerShell .Net Assembly, so there is likely a misunderstanding on my part.

I generated PowerShell .Net Assebly code from WinSCP, when I try to use it, I get an error. What am I doing wrong please?

CODE:

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

# Set up session options
$sessionOptions = New-Object WinSCP.SessionOptions -Property @{
    Protocol = [WinSCP.Protocol]::Sftp
    HostName = "sftp site"
    UserName = "username"
    Password = "`password"
    SshHostKeyFingerprint = "securitydata"
}

$sessionOptions.AddRawSettings("FSProtocol", "2")

$session = New-Object WinSCP.Session

try
{
    # Connect
    $session.Open($sessionOptions)
    Write-Host $session
    # Set up transfer options
    $transferOptions = New-Object WinSCP.TransferOptions -Property @{
        TransferMode = [WinSCP.TransferMode]::Ascii
    }
    
    # Transfer files
    #changed 
}
finally
{
    $session.Dispose()
}

ERROR:

MethodInvocationException: untitled:Untitled-3:19:5
Line |
  19 |      $session.Open($sessionOptions)
     |      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     | Exception calling "Open" with "1" argument(s): "Method not found: 'Void System.Threading.EventWaitHandle..ctor(Boolean, System.Threading.EventResetMode, System.String, Boolean ByRef,
     | System.Security.AccessControl.EventWaitHandleSecurity)'."
JM1
  • 1,595
  • 5
  • 19
  • 41
  • Thanks @MartinPrikryl! I see I need to use the .NET Standard build of the WinSCP .NET assembly. I've read the instructions on the website, but I still don't understand what I need to do. Do I place the WinSCPnet.dll from the NetStandard directory in the same directory as the PowerShell .exe? Then, in the script, do I point the Add-Path to that .dll? LIke this? Add-Type -Path "C:\Windows\System32\WindowsPowerShell\v1.0\WinSCPnet.dll" – JM1 Oct 24 '22 at 11:41
  • Sorry, I don't have much experience understanding how to integrate or install .Net items in PowerShell, but I appreciate your help! – JM1 Oct 24 '22 at 11:45
  • Based on `Add-Type -Path "WinSCPnet.dll"`, I assume you already have a `net40` copy of the `WinSCPnet.dll`, in the folder where your PowerShell script resides. Replace that copy (or whatever copy your PowerShell script loads) with the `netstandard2.0` version. – Martin Prikryl Oct 24 '22 at 11:51
  • Thanks. Yes, I have a copy of the WinSCPnet.dll, but I just didn't know where to place it. It looks like it needs to be in the same file location as the PowerShell script that I am running, is that correct? If so, do I need to use Set-Location in the PowerShell script as well, or is just having it in the same directory as the .ps1 script sufficient? – JM1 Oct 24 '22 at 12:22
  • 1
    The `Add-Type -Path "WinSCPnet.dll"` loads the dll from *somewhere* (probably the script's folder). So if you replace that copy with the `netstandard2.0` version, it will work with no other effort. – Martin Prikryl Oct 24 '22 at 12:32

0 Answers0