使用Powershell删除文件

问题描述 投票:-1回答:2

我有一个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:无法获取文件的属性

不知道这意味着什么。

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

powershell winscp
2个回答
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循环后关闭会话。也许你已经这样做了,但它没有显示在你的代码中。


Putting it together with your code:
$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)
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.