Avatar of rwheeler23
rwheeler23
Flag for United States of America

asked on 

Powershell script fails with error code (0x1)

I have this Powershell script that uses WinSCP to upload a file. This code is sample from their documentation. I have supplied the sessions options but when I run this script it returns error code (0x1). I am running this script with this command.


powershell.exe -NoProfile -NoLogo -NonInteractive -ExecutionPolicy Bypass -File "C:\GPShares\Automation\Powershell\HMSVAutoXfer.ps1"

-------------------------------------------------------------------

# HMSVAutoXfer.ps1 - transfer most recent file to server

try
{
    # Load WinSCP .NET assembly
    Add-Type -Path "WinSCPnet.dll"
 
    # Setup session options
    $sessionOptions = New-Object WinSCP.SessionOptions -Property @{
        Protocol = [WinSCP.Protocol]::Sftp
        HostName = ""
        UserName = ""
        Password = ""
        SshHostKeyFingerprint = ""
    }
 
    $session = New-Object WinSCP.Session
 
    try
    {
        # Connect
        $session.Open($sessionOptions)
 
        $localPath = "C:\GPShares\ImportFiles\SOPExport"
        $remotePath = "/upload"
 
        # Select the most recent file.
        # The !$_.PsIsContainer test excludes subdirectories.
        # With PowerShell 3.0, you can replace this with -File switch of Get-ChildItem.
        $latest =
            Get-ChildItem -Path $localPath |
            Where-Object {!$_.PsIsContainer} |
            Sort-Object LastWriteTime -Descending |
            Select-Object -First 1
 
        # Any file at all?
        if ($latest -eq $Null)
        {
            Write-Host "No file found"
            exit 1
        }
 
        # Upload the selected file
        $session.PutFiles(
            [WinSCP.RemotePath]::EscapeFileMask($latest.FullName),
            [WinSCP.RemotePath]::Combine($remotePath, "*")).Check()
    }
    finally
    {
        # Disconnect, clean up
        $session.Dispose()
    }
 
    exit 0
}
catch
{
    Write-Host "Error: $($_.Exception.Message)"
    exit 1
}

Powershell.NET Programming

Avatar of undefined
Last Comment
footech

8/22/2022 - Mon