-2

我有一个 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()
}
4

1 回答 1

-1

我通过将脚本从任务计划移动到 SQL Server 代理作业来修复它。现在它完美无缺。

感谢您的所有反馈和建议。

于 2019-05-16T07:16:14.557 回答