send_zjshuju_report.ps1:

# ZJShuju 近3天报表发邮件 - 计划任务脚本
# 手动测试请双击【运行报表发邮件.bat】
# 注意:每执行一次就会发一封邮件,请勿重复运行

$logFile = Join-Path $PSScriptRoot "zjshuju_report.log"
$url     = "http://120..服务器ip/api/ZJShujuReport/SendLast3Days?token=MH2024ZJReport_x8k2p9"
$exitCode = 0

function Write-Log($text) {
    $line = "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') $text"
    Add-Content -Path $logFile -Value $line -Encoding UTF8
    Write-Host $line
}

Write-Log "========== 开始执行 =========="
Write-Log "脚本目录: $PSScriptRoot"

try {
    Write-Log "检测端口 8766..."
    $conn = Test-NetConnection -ComputerName "120.7服务器ip" -Port 8766 -WarningAction SilentlyContinue
    if (-not $conn.TcpTestSucceeded) {
        Write-Log "失败: 无法连接 120.7服务器ip"
        $exitCode = 1
    } else {
        Write-Log "端口 8766: 通"
        Write-Log "开始请求: $url"
        Write-Log "接口请求中,请等待(查数据+发邮件可能需要1~3分钟)..."

        [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
        $response = Invoke-WebRequest -Uri $url -UseBasicParsing -TimeoutSec 300

        $body = $response.Content
        if ($body -match '"code"\s*:\s*"0"') {
            Write-Log "成功 HTTP $($response.StatusCode): $body"
        } else {
            Write-Log "失败 HTTP $($response.StatusCode): $body"
            $exitCode = 1
        }
    }
} catch {
    $detail = $_.Exception.Message
    if ($_.Exception.Response) {
        try {
            $reader = New-Object System.IO.StreamReader($_.Exception.Response.GetResponseStream())
            $detail = $detail + " | " + $reader.ReadToEnd()
        } catch { }
    }
    Write-Log "失败: $detail"
    $exitCode = 1
} finally {
    Write-Log "========== 执行结束 =========="
}

exit $exitCode

创建定时任务bat:

@echo off
chcp 65001 >nul
title 创建计划任务 - ZJShujuReport_Email

set TASK_NAME=ZJShujuReport_Email
set PS_EXE=C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
set PS1_FILE=%~dp0send_zjshuju_report.ps1

echo.
echo 任务名称: %TASK_NAME%
echo 脚本路径: %PS1_FILE%
echo 执行时间: 每3天 17:30
echo.

if not exist "%PS1_FILE%" (
    echo 错误: 找不到 send_zjshuju_report.ps1
    pause
    exit /b 1
)

schtasks /create /tn "%TASK_NAME%" /tr "\"%PS_EXE%\" -NoProfile -ExecutionPolicy Bypass -File \"%PS1_FILE%\"" /sc daily /mo 3 /st 17:30 /f

if %ERRORLEVEL%==0 (
    echo.
    echo ===== 计划任务创建成功 =====
    echo.
    echo 手动测试: schtasks /run /tn "%TASK_NAME%"
    echo 查看日志: %~dp0zjshuju_report.log
) else (
    echo.
    echo ===== 创建失败,请以管理员身份运行本 bat =====
)

echo.
pause
 

Logo

openEuler 是由开放原子开源基金会孵化的全场景开源操作系统项目,面向数字基础设施四大核心场景(服务器、云计算、边缘计算、嵌入式),全面支持 ARM、x86、RISC-V、loongArch、PowerPC、SW-64 等多样性计算架构

更多推荐