Skip to content

Instantly share code, notes, and snippets.

@hagerliu
Last active November 18, 2023 05:02
Show Gist options
  • Select an option

  • Save hagerliu/c4ba5d310e0095a0fc67d894da8f7dd6 to your computer and use it in GitHub Desktop.

Select an option

Save hagerliu/c4ba5d310e0095a0fc67d894da8f7dd6 to your computer and use it in GitHub Desktop.
配合计划任务每小时循环
$OutputEncoding = [System.Text.Encoding]::UTF8
# 设置代理服务器地址和端口
$proxy = "http://127.0.0.1:2080"
# 共同部分的链接
$baseDownloadUrl = "https://github.com/hagerliu/v2ray-rules-dat/raw/release/"
# 设置解压目标目录
$targetDirectory = "C:\portapps\nekoray"
# 获取临时目录
$tempDirectory = $targetDirectory
# 设置文件下载地址和文件名
$url = $baseDownloadUrl + "sing-box-geodata.zip"
$outputFile = Join-Path $tempDirectory "sing-box-geodata.zip"
$sha256sumUrl = $url + ".sha256sum"
# 设置clashApi参数
$ip_port = ""
$secret = ""
# 设置重试次数
$maxRetries = 3
$currentRetry = 0
# 获取进程名
$programPath = "C:\portapps\nekoray\nekoray.exe"
$processName = (Get-Item $programPath).BaseName
# 判断程序运行和geosite文件的修改时间
try {
$runningProcesses = Get-Process -Name $processName -ErrorAction Stop
$geositeDbCreationTime = (Get-Item (Join-Path $targetDirectory "geosite.db")).CreationTime
$midnight4AM = (Get-Date).Date.AddHours(4)
if ($geositeDbCreationTime -ge $midnight4AM -and $runningProcesses) {
Write-Host "geosite.db 文件创建时间在今天的凌晨4点以后,$processName 进程正在运行,脚本结束。"
exit
}
}
catch {
Write-Host "进程 $processName 未在运行。"
}
# 循环尝试下载和验证文件
do {
# 删除已存在的文件
Remove-Item $outputFile -ErrorAction SilentlyContinue
Remove-Item "$outputFile.sha256sum" -ErrorAction SilentlyContinue
# 下载文件
Invoke-WebRequest -Uri $url -Proxy $proxy -OutFile $outputFile -UseBasicParsing
# 下载sha256sum文件
Invoke-WebRequest -Uri $sha256sumUrl -Proxy $proxy -OutFile "$outputFile.sha256sum" -UseBasicParsing
# 计算下载文件的sha256值
$downloadedSha256 = Get-FileHash -Path $outputFile -Algorithm SHA256 | Select-Object -ExpandProperty Hash
# 读取期望的sha256值
$sha256sum = Get-Content "$outputFile.sha256sum"
$expectedSha256 = ($sha256sum -split ' ')[0]
# 检查两个值是否不为空且匹配
if ($downloadedSha256 -and $expectedSha256 -and ($downloadedSha256 -eq $expectedSha256)) {
Write-Host "文件完整性验证通过"
break
} else {
Write-Host "文件完整性验证未通过,重新尝试下载..."
$currentRetry++
}
} while ($currentRetry -lt $maxRetries)
# 检查是否达到最大重试次数
if ($currentRetry -eq $maxRetries) {
Write-Host "达到最大重试次数,无法验证文件完整性。"
} else {
# 解压文件到目标目录
Expand-Archive -Path $outputFile -DestinationPath $targetDirectory -Force
Write-Host "文件解压完成并覆盖到目标目录: $targetDirectory"
# 删除临时文件
Remove-Item $outputFile
Remove-Item "$outputFile.sha256sum"
#重载配置
$endpoint = "http://$ip_port/configs?force=true"
try {
$response = Invoke-RestMethod -Uri $endpoint -Method Put -Headers @{"Authorization" = "Bearer $secret"} -Body '{"path": "", "payload": ""}' -ErrorAction Stop
Write-Host "$bin_name 配置重载成功。"
} catch {
Write-Host "$bin_name 配置重载失败!"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment