我有一个 PowerShell 脚本,它使用 WinSCP .Net 库从 FTP 服务器获取一些文件。
该脚本使用任务计划程序从管理员帐户在服务器上自动运行一夜。
问题是有时(它没有模式,或者至少我无法弄清楚)它会给我一个错误:“对象引用未设置为对象的实例”。
错误:
使用“1”参数调用“打开”的异常:“对象引用未设置为
一个对象的实例。”
在 C:\user\blabla\powershellscript.ps1:47
字符:5
+ $session.Open($sessionOptions)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId:NullReferenceException
代码中的实际行(第 47 行)是 : $session.Open($sessionOptions)。
如果我从任务计划程序运行脚本或任务,它运行顺利并且不会给我任何错误。
PowerShell 脚本:
Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope Process
$FileSourcePath = '/path_to_the_file'
Add-Type -Path "C:\WinSCP\WinSCPnet.dll"
# Set up session options
$sessionOptions = New-Object WinSCP.SessionOptions -Property @{
Protocol = [WinSCP.Protocol]::Sftp
HostName = "ip_to_the_server"
UserName = "correct_username"
Password = "correct_password"
SshHostKeyFingerprint = "correct_sshrsa_fingerprint"
}
$session = New-Object WinSCP.Session
try {
# Connect
$session.Open($sessionOptions)
# Transfer files
$session.GetFiles($FileSourcePath, $FileDestinationPath).Check()
} catch {
$_ | Out-File c:\blabla\errors.txt -Append
} finally {
$session.Dispose()
}