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
}
ASKER
ASKER
ASKER
$session.Open($sessionOptions)
and it fails because something is wrong with:
$sessionOptions = New-Object WinSCP.SessionOptions -Property @{
Protocol = [WinSCP.Protocol]::Sftp
HostName = ""
UserName = ""
Password = ""
SshHostKeyFingerprint = ""
I have used WinSCP to obtain these values. Is there any way to confirm this? If so, I can ask those who setup the SFTP server for the correct connection values.
You may want to comment out the "exit 1" for debugging if it's closing your session while trying to debug. The info you get from Write-Host "Error: $($_.Exception.Message)" may be limited depending on the error. You can output the full $error[0] or other properties of it to examine more.
ASKER
catch
{
Write-Host "Error: $($_.Exception.Message)"
#exit 2
}
ASKER
catch
{
Write-Host $error[0]
exit 2
}
Running this just returns (0x2)
ASKER
Write-Host ("Error: {0}" -f $_.Exception.Message)
You should set another error code for "no file found". (exit 2).
We will know if the error code is coming from the Catch or from the file not found.