使用Powershell删除文件

时间:2019-04-24 10:32:43

标签: powershell winscp

我有一个Powershell脚本,该脚本每2分钟连接到SFTP并删除文件。如果文件没有被删除,它将重试10次。

代码:

$session = New-Object WinSCP.Session

$retryTimes = 0

while ($retryTimes -ne 10) {

  try {
    $retryTimes++
    $session.Open($sessionOptions)
    echo ("Opened a session with options: " + $sessionOptions)
    echo ("Trying to remove a file: " + $fileToRemove)
    $fileToRemove = "/File_$((Get-Date).AddDays(-1).ToString("yyyyMMdd_HHmm")).csv"
    $session.RemoveFiles($fileToRemove)
    echo ("File" + $fileToRemove + "removed." )
    }
   catch {
    echo ("File not removed retrying for the " + $retryTimes + "time.")
    echo ($Error[0].Exception)
  }
  }

我注意到它有时每2分钟运行一次并不会删除文件,有时它不会删除文件。

我检查了日志,发现错误-{} {WinSCP.SessionRemoteException:无法获取文件的属性

不确定这是什么意思。

有没有办法确保删除文件?

2 个答案:

答案 0 :(得分:1)

  

无法获取文件属性

肯定会在错误/日志文件中包含更多详细信息,这将告诉我们根本原因。

但是很可能意味着该文件根本不存在。

答案 1 :(得分:1)

我同意Martin Prikryl的观点,即您所追求的文件可能不存在。 您可以使用以下方法进行检查以找出文件是否存在:

if ($session.FileExists($fileToRemove)) {
    $session.RemoveFiles($fileToRemove).Check()
    Write-Host "File '$fileToRemove' removed."
    # exit the while loop, because the action succeeded
    break
}
else {
    Write-Host "File '$fileToRemove' not found."
}

此外,我将在使用$session.Close的while循环后关闭会话。也许您已经这样做了,但是它不会显示在您的代码中。


将其与您的代码放在一起:

$session = New-Object WinSCP.Session

$retryTimes = 0

while ($retryTimes -ne 10) {
    try {
        $retryTimes++
        $session.Open($sessionOptions)
        echo ("Opened a session with options: " + $sessionOptions)
        echo ("Trying to remove a file: " + $fileToRemove)
        $fileToRemove = "/File_$((Get-Date).AddDays(-1).ToString("yyyyMMdd_HHmm")).csv"

        if ($session.FileExists($fileToRemove)) {
            # we know now that the file actually exists, so the next line should not throw the exception
            $session.RemoveFiles($fileToRemove)
            Write-Output "File '$fileToRemove' removed."
            # exit the while loop, because the action succeeded
            break
        }
        else {
            Write-Output "File '$fileToRemove' not found."
        }

    }
    catch {
        # some other exception happened
        echo ("File not removed retrying for the " + $retryTimes + " time.")
        echo ($Error[0].Exception)
    }
}