powershellsftpposh-ssh

Does Posh-ssh not work with windows Task Scheduler


Been trying to connect to an sftp using posh-ssh. Works fine when i run it, when i try running it through windows task scheduler it does not work.

I have tried switching around the users that are to run the script such as Admin, myself, system, etc.

I have tried using keys to save the password and decrypt it later on.

$Password = ConvertTo-SecureString 'sftpPW' -AsPlainText -Force
$Credential = New-Object System.Management.Automation.PSCredential($SFTPUser, $Password) 
$sftpIP = 'hostIP'
$sftpSess = New-SFTPSession -ComputerName $SftpIp -Credential $Credential

And then other method VVVVVVVVVV this part is run not in the script but is to create a password

Get-Random -Count 32 -InputObject (0..255) | Out-File -FilePath encrypt
ConvertTo-SecureString 'sftpPW' -AsPlainText -Force | convertFrom-secureString -key (get-content -path encrypt) | Out-File pw

^^^^^^^^^^

$SFTPUser="user"
$password = (cat pw | ConvertTo-SecureString -key (Get-Content -path encrypt))
$Credential = New-Object System.Management.Automation.PSCredential($SFTPUser, $Password) 
$sftpIP = 'hostIP'
$sftpSess = New-SFTPSession -ComputerName $SftpIp -Credential $Credential

edit*

Import-Module Posh-SSH
$datestuff = Get-Date
echo "start $datestuff" > C:\sftptestlog
$SFTPUser="user"
echo $sftpuser >> C:\sftptestlog
$Password = ConvertTo-SecureString 'sftpPW' -AsPlainText -Force
echo $password >> C:\sftptestlog
$Credential = New-Object System.Management.Automation.PSCredential($SFTPUser, $Password) 
$sftpIP = 'hostip'

echo $Credential >> C:\sftptestlog
echo $sftpip >> C:\sftptestlog
$sftpSess = New-SFTPSession -ComputerName $SftpIp -Credential $Credential
echo $sftpSess >> C:\sftptestlog

expected output from sftptestlog

start 09/10/2019 16:31:19

user

System.Security.SecureString

UserName Password

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

user System.Security.SecureString

hostIP

SessionId Host Connected

--------- ---- ---------
2 hostIP True

above output only happens when the script is run from the command line. When using scheduler the output is the same only the last lines (starting from sessionID) are not printed out.


Solution

  • Found out that the ENV:PSModulePath didn't have the path to where the module was installed when using task scheduler. When importing the module I linked directly to where the module was. Import-Module "C:\Program Files\WindowsPowerShell\Modules\Posh-SSH"