001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
# testSftpConnect.ps1
# Quick script to test SFTP connectivity
 
$username='FTPUSER'
$password='PASSWORD'
$sftpServer='x.x.x.x'
$sftpPort=22
 
function testSftpConnect($sftpServer,$username,$password,$sftpPort){
  
    function includePowerShellWrapper($appName){
        # Ensure that PowerShell is using TLS 1.2 in this session
        [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
        # Uncomment these lines to make TLS1.2 defaults on next reboot
        #Set-ItemProperty -Path 'HKLM:\SOFTWARE\Wow6432Node\Microsoft\.NetFramework\v4.0.30319' -Name 'SchUseStrongCrypto' -Value '1' -Type DWord
        #Set-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\.NetFramework\v4.0.30319' -Name 'SchUseStrongCrypto' -Value '1' -Type DWord   
   
        # Deterministic verification on whether module commands are able to load
        Import-Module $appName -ea SilentlyContinue
        # Sanity check: validate module name before proceeding
        $moduleVersion=.{$y=find-module $appName -ea SilentlyContinue;if($y){return $y.Version.ToString()}}
        if(!$moduleVersion){write-warning "'$($appName.ToUpper())' doesn't match PowerShell module";return $false}  
        elseif(!$moduleIsLoaded){
            # Part A) Compare the installed module with its online counter-part; install if necessary
            # Select Major, Minor, and Build - omitting Revision.
            # This is because PowerShell wrapper will deem an installed binary as compatible as long as those values match    
            $installedVersion=.{$x=Get-Module $appName -ea SilentlyContinue;if($x){return $x.Version.ToString()}}
            $targetVersion=.{try{[void]($moduleVersion -match '^(\d+\.\d+\.{0,1}\d+)');$matches[1]}catch{}}
            if($matches){Clear-Variable -name matches}
            write-host "$($appName.ToUpper()) PowerShell wrapper`: Installed $installedVersion v.s Updated version $moduleVersion"
            if($installedVersion -ne $moduleVersion){
                write-host "Attempting to install the module $appName $moduleVersion"
                Remove-Module $appName -ea SilentlyContinue
                try{               
                    Install-Module -Name $appName -Force -Confirm:$false;
                    Import-Module $appName;
                    write-host "$appName PowerShell wrapper module has been installed."
                    return $true
                    }
                catch{
                    if(!('NuGet' -in (get-packageprovider).Name)){   
                        try{
                            Install-PackageProvider -Name NuGet -MinimumVersion '2.8.5.201' -Force -Confirm:$false -ErrorAction Stop;
                            Install-Module -Name $appName -Force -Confirm:$false;
                            Import-Module $appName;
                            write-host "$appName PowerShell wrapper module has been installed."
                            }
                        catch{                 
                            write-host "$error"
                            write-warning "Unable to install $appName module"
                            return $false
                            }           
                        }
                    }
                }
   
            # Part B) Check Installed applications and upgrade/downgrade as necessary
            $installedApps=Get-CimInstance -ClassName win32_InstalledWin32Program -ErrorAction SilentlyContinue|select Name,Version
            $appwizAppExists=.{try{$matchApp=$installedApps|?{$_.Name -like "*$appName*"|select -First 1 }
                                if($matchApp){$matchApp}else{$false}}catch{}}
            $appwizVersion=.{try{[void]($(if($appwizAppExists){$appwizAppExists.Version}else{$false}) -match '^(\d+\.\d+\.{0,1}\d+)');$matches[1]}catch{}}
            if($matches){Clear-Variable -name matches}
            write-host "Application Wizard version being detected: $appwizAppExists"
            $isAppwizSameVersion=$targetVersion -eq $appwizVersion
       
            $chocoInstalledApps=choco list -l
            $chocoAppExists=$chocoInstalledApps|?{$_ -like "*$appName*"}|select -First 1
            $chocoVersion=.{try{[void]($(.{[void]($chocoAppExists -match ' ([\d+\.]+)');return $matches[1]}) -match '^(\d+\.\d+\.{0,1}\d+)');$matches[1]}catch{}}
            if($matches){Clear-Variable -name matches}
            write-host "Choco version being detected: $chocoAppExists"
            $isChocoSameVersion=$targetVersion -eq $chocoVersion
            write-host "Target version: $targetVersion, Appwiz version: $appwizVersion, Choco version: $chocoVersion"
       
            if (!($isAppwizSameVersion -or $isChocoSameVersion)){       
                write-host "Now trying to install $appname..."
                    if (!(Get-Command choco.exe -ErrorAction SilentlyContinue)) {
                        Set-ExecutionPolicy Bypass -Scope Process -Force; iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))}
                    try{
                        if(!$chocoAppExists -and !$appwizAppExists){choco install $appName --version=$targetVersion -y}
                        elseif (!$isChocoSameVersion -and !$isAppwizSameVersion){choco install $appName --version=$targetVersion --force -y}
                        write-host "Application $appName $targetVersion is now installed"
                        if($matches){Clear-Variable -name matches}
                        return $true
                    }
                    catch{
                        write-warning "Unable to install the app name $appName $targetVersion using Chocolatey."
                        if($matches){Clear-Variable -name matches}
                        return $false
                        }
                }
            else{
                write-host "$appName is already installed.";
                if($matches){Clear-Variable -name matches}
                return $true}
        }
        else{write-host "$($appName.ToUpper()) module has loaded successfully.";return $true}
    }
  
    function connectWinScp{
        param (
            $remoteHost,
            $username,
            $password,
            $port=22,
            $hostKey,
            $privateKey
            )
        Import-Module WinScp -ea SilentlyContinue
        # Possible error:
        # Import-Module : The specified module 'WinScp' was not loaded because no valid module file was found in any module
        # directory.
        # At line:102 char:15
        # +         $null=Import-Module WinScp
        # +               ~~~~~~~~~~~~~~~~~~~~
        #     + CategoryInfo          : ResourceUnavailable: (WinScp:String) [Import-Module], FileNotFoundException
        #     + FullyQualifiedErrorId : Modules_ModuleNotFound,Microsoft.PowerShell.Commands.ImportModuleCommand
        #         $moduleIsLoaded=Get-Command -Module $appName -ea SilentlyContinue
        if(!(get-module Winscp)){
            includePowerShellWrapper Winscp
            Import-Module WinScp
            }
        # if ($scpSession){ # deal with case that the global variable $scpSession has already been assigned
        #     try{
        #         Close-WinSCPSession -WinSCPSession $scpSession -ea SilentlyContinue
        #         $scpSession.Dispose()
        #     }catch{
        #         Clear-Variable scpSession
        #         }
        #     }
         $optionValues="
            `$options = New-Object WinSCP.SessionOptions -Property @{
                # source: https://winscp.net/eng/docs/library_sessionoptions
                Protocol = [WinSCP.Protocol]::Sftp
                HostName = '$remoteHost'
                username = '$username'
                portnumber = '$port'
                $(if($hostKey){"SshHostKeyFingerprint = '$hostKey'"}else{"GiveUpSecurityAndAcceptAnySshHostKey = `$True"})
                $(if($privateKey){"SshPrivateKeyPath = '$privateKey'"}else{"password = '$password'"})
            }"
         try{
            write-host $optionValues
            Invoke-Expression $optionValues
            $scpSession =  Open-WinSCPSession -SessionOption $options -ea Stop
            write-host "WinSCP has successfully connected to $remoteHost" -ForegroundColor Green
            return $scpSession
            }
        catch{
            write-waring $_
            write-host "unable to connnect to $remoteHost" -ForegroundColor Yellow
            return $false
            }
    }
  
    $scpSession=connectWinScp $sftpServer $username $password $sftpPort
    if($scpSession){
        write-host "Now closing test WinScp session"
        Close-WinSCPSession -WinSCPSession $scpSession
        # $scpSession.dispose() # alternate cleanup routine
        return $true
    }else{
        return $false
        }
}
  
testSftpConnect $sftpServer $username $password $sftpPort