You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改WinSCP PowerShell脚本以显示远程文件存在状态

修改WinSCP脚本实现文件存在性检查与缺失提示

以下是修改后的PowerShell脚本,保留了原脚本的远程文件夹存在性检查功能,同时新增了输出远程服务器上找到的文件和提示指定日期区间内缺失的日志文件的功能:

# 设置会话选项
$options = @{
    Protocol = [WinSCP.Protocol]::Sftp
    HostName = $entry.IP
    UserName = $User
    Password = $Password
    GiveUpSecurityAndAcceptAnySshHostKey = $true
}

try {
    # 使用第一组配置尝试连接
    $sessionOptions = New-Object WinSCP.SessionOptions -Property $options
    $session = New-Object WinSCP.Session
    $session.Open($sessionOptions)
} 
catch {
    # 第一组连接失败,使用VPN配置尝试
    $options['HostName'] = $vpnIP
    $options['UserName'] = $User
    $options['Password'] = $Password
    try {
        $sessionOptions = New-Object WinSCP.SessionOptions -Property $options
        $session = New-Object WinSCP.Session
        $session.Open($sessionOptions)
    }
    catch {
        Write-Error "无法打开WinSCP会话: $($_.Exception.Message)"
        throw
    }
}

# 输入开始日期(包含)
do {
    $date = $null
    $today = Read-Host -Prompt "请输入开始日期(包含),格式为 yyyy.MM.dd(示例:$(Get-Date -Format "yyyy.MM.dd"))"

    try {
        $date = Get-Date -Date $today -Format "yyyy-MM-dd" -ErrorAction Stop
        "[OK] $date 日期格式有效!"
    }
    catch {
        "[X] $today 日期格式无效,请重新输入!"
    }
}
until ($date)

# 输入结束日期(不包含)
do {
    $date1 = $null
    Write-Host "注意:结束日期为**不包含**,如需包含结束日请输入次日日期" -ForegroundColor Red
    $today1 = Read-Host -Prompt "请输入结束日期(不包含),格式为 yyyy.MM.dd(示例:$(Get-Date -Format "yyyy.MM.dd"))"

    try {
        $date1 = Get-Date -Date $today1 -Format "yyyy-MM-dd" -ErrorAction Stop
        "[OK] $date1 日期格式有效!"
    }
    catch {
        "[X] $today1 日期格式无效,请重新输入!"
    }
}
until ($date1)

# 生成日期区间内的所有日期(包含开始,不包含结束)
$dateRange = (Get-Date $date)..(Get-Date $date1).AddDays(-1) | ForEach-Object { $_.ToString("yyyy-MM-dd") }

$localPath = "\temp_files" 
$remotePaths = "/C:/log", "/C:/Back_up" # 变量名修改为复数避免循环内覆盖

try {
    # 遍历每个远程文件夹
    foreach ($remotePath in $remotePaths)
    {
        if ($session.FileExists($remotePath))
        {
            Write-Host "[OK] 文件夹 '$remotePath' 存在" -ForegroundColor Green

            Write-Host "[i] 正在处理日期区间 '$date' - '$date1' 的文件..." -ForegroundColor Cyan

            # 获取远程文件夹中符合日期条件的所有.log文件
            $remoteFiles = $session.ListDirectory($remotePath).Files | Where-Object {
                !$_.IsDirectory -and $_.Name -like "*.log" -and $_.LastWriteTime -ge (Get-Date $date) -and $_.LastWriteTime -lt (Get-Date $date1)
            }

            # 输出找到的文件列表
            if ($remoteFiles.Count -gt 0)
            {
                Write-Host "[找到的文件] 在 '$remotePath' 中发现以下日志文件:" -ForegroundColor Cyan
                $remoteFiles | ForEach-Object { Write-Host "  - $($_.Name)" }
            }
            else
            {
                Write-Host "[提示] 在 '$remotePath' 中未找到符合日期条件的.log文件" -ForegroundColor Yellow
            }

            # 检查每个日期是否存在对应文件
            foreach ($targetDate in $dateRange)
            {
                $targetDateObj = Get-Date $targetDate
                $hasMatchingFile = $remoteFiles | Where-Object {
                    $_.LastWriteTime.Date -eq $targetDateObj.Date
                }
                if (-not $hasMatchingFile)
                {
                    Write-Host "[缺失] 日期 $targetDate 的 *.log 文件在远程服务器上不存在" -ForegroundColor Red
                }
            }

            # 执行文件下载
            Write-Host "[i] 开始下载文件到本地路径 '$localPath'..." -ForegroundColor Cyan
            $transferResult = $session.GetFilesToDirectory($remotePath, $localPath, "*.log>=$date<=$date1")
            $transferResult.Check() # 检查下载是否有错误
            Write-Host "[完成] '$remotePath' 的文件下载完成" -ForegroundColor Green
        }
        else
        {
            Write-Host "[错误] 文件夹: '$remotePath' 不存在" -ForegroundColor Red
        }
    }
}
finally {
    # 释放会话资源
    $session.Dispose()
}

关键修改说明

  • 修正会话重复创建问题:移除原脚本中重复创建$session的代码,避免覆盖已建立的连接
  • 生成日期区间列表:创建包含开始日期到结束日期前一天的所有日期,用于逐个检查文件存在性
  • 获取并输出远程文件:先列出远程文件夹中符合日期条件的日志文件,直接输出找到的文件名称
  • 缺失文件检测:对比日期列表和远程文件的修改日期,找出没有对应文件的日期并给出红色提示
  • 优化提示信息:调整提示文字的清晰度和颜色区分,便于快速识别状态

内容的提问来源于stack exchange,提问作者SySx

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 23:04:51