Posh-ssh 不能与 windows Task Scheduler 一起使用吗

Does Posh-ssh not work with windows Task Scheduler

一直在尝试使用 posh-ssh 连接到 sftp。当我 运行 它时工作正常,当我尝试 运行 通过 windows 任务调度程序时它不起作用。

我试过切换运行脚本的用户,例如管理员、我自己、系统等

我试过使用密钥保存密码并稍后解密。

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

然后其他方法 VVVVVVVVVVV 这部分 运行 不在脚本中,而是用于创建密码

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

编辑*

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

sftptestlog 的预期输出

2019 年 9 月 10 日开始 16:31:19

用户

System.Security.SecureString

用户名密码

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

用户System.Security.SecureString

主机IP

SessionId 主机已连接

------------------------
2 主机 IP 真

以上输出仅当脚本是来自命令行的 运行 时才会发生。使用调度程序时,输出是相同的,只是最后一行(从 sessionID 开始)没有被打印出来。

我强烈建议您在脚本中加入一些日志记录,这样您就可以诊断这类事情,因为任务计划程序事件日志根本帮不上什么忙。一种简单的方法是使用 Start-Transcript

# Put this line at the very start of your script
Start-Transcript -Path 'c:\temp\sftplog.txt'

Write-Host 'Setting up user credentials'
$Password = ConvertTo-SecureString 'sftppassword' -AsPlainText -Force
$SFTPUser="username"
$Credential = New-Object System.Management.Automation.PSCredential($SFTPUser, $Password) 

# Destination host
$sftpIP = 'hostip'
Write-Host 'Destination host is $sftpIP, testing availability'
Try {
    Test-Connection -ComputerName $sftpIP -ErrorAction Stop
    Write-Host 'Host is contactable'
}
Catch {
    $_.Exception
}


# Attempt connection
Try {
    Write-Host 'Trying to connect via SFTP to $SftpIP'
    $sftpSess = New-SFTPSession -ComputerName $SftpIp -Credential $Credential -ErrorAction Stop
    Write-Host 'Done'
}
Catch {
    $_
}

# Put this line at the very end of your script
Stop-Transcript

您可以在诊断出问题后删除 Transcript and/or 所有 Write-Host 命令。

发现 ENV:PSModulePath 在使用任务调度程序时没有安装模块的路径。导入模块时,我直接链接到模块所在的位置。 Import-Module "C:\Program Files\WindowsPowerShell\Modules\Posh-SSH"

为避免 posh-ssh 模块的路径出现问题,您可以使用以下方式安装它:

安装模块 posh-ssh -Scope AllUsers