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

PowerShell脚本需求:投票数据提取、累计合并及达标标记

PowerShell脚本开发需求及解决方案

功能需求

  • 从JSON格式的.txt文件中提取username与votecount字段
  • 单期投票数≥25时,需记录该期达标状态
  • 将新数据与已存在的输出文件中的历史数据累加合并:
    • 示例1:第1周testuser投票25次 → 输出testuser,25D
    • 示例2:第2周该用户投票24次 → 累计49次,因有过1次达标记录,输出testuser,49D
    • 示例3:第2周该用户再次投票25次 → 累计50次,2次达标,输出testuser,50D2
  • 支持批量处理100+用户

输入数据格式(示例.txt)

{
    "username": "testuser",
    "votecount": "42",
    "votesclaimed": "0",
    "lastvotetime": "2022-11-04 09:08:29",
    "steamid": "00000000000000000000"
}

现有脚本问题

  1. 使用了不存在的ConvertFrom-txt cmdlet,实际应为ConvertFrom-Json
  2. 未实现历史数据合并逻辑
  3. D标记判断条件错误(用了-gt 25,需求是≥25)
  4. 未记录达标次数,无法支持多次达标的累计展示

修正后的脚本

# 定义文件路径
$newDataPath = "C:\Users\--------\Desktop\votes.txt"
$historyFilePath = "C:\Users\---------\Desktop\outvotes.csv"

# 读取并解析新的投票数据
$newVotes = Get-Content -Raw $newDataPath | ConvertFrom-Json | ForEach-Object {
    [pscustomobject]@{
        UserName       = $_.username
        CurrentVotes   = [int]$_.votecount
        HasQualified   = [int]$_.votecount -ge 25  # 标记本期是否达标
    }
}

# 读取历史数据(如果文件存在)
if (Test-Path $historyFilePath) {
    $historyData = Import-Csv $historyFilePath | ForEach-Object {
        # 解析历史记录中的累计票数和达标次数
        $voteMatch = $_.VoteCount -match '^(\d+)(D(\d+)?)$'
        [pscustomobject]@{
            UserName       = $_.UserName
            TotalVotes     = [int]$matches[1]
            QualifiedTimes = if ($matches[3]) { [int]$matches[3] } else { 1 }
        }
    }
} else {
    $historyData = @()
}

# 合并新数据与历史数据
$mergedData = foreach ($newVote in $newVotes) {
    $existing = $historyData | Where-Object UserName -eq $newVote.UserName
    if ($existing) {
        # 累计票数,累加达标次数
        $total = $existing.TotalVotes + $newVote.CurrentVotes
        $qualifiedTimes = $existing.QualifiedTimes + $newVote.HasQualified
    } else {
        # 新用户,初始化数据
        $total = $newVote.CurrentVotes
        $qualifiedTimes = $newVote.HasQualified
    }

    # 格式化输出字符串:票数 + D + 达标次数(次数为0则不显示)
    $voteDisplay = if ($qualifiedTimes -gt 0) {
        "$total D$qualifiedTimes" -replace " D1$", "D"  # 达标1次时简化为D
    } else {
        "$total"
    }

    [pscustomobject]@{
        UserName   = $newVote.UserName
        VoteCount  = $voteDisplay.Trim()
    }
}

# 导出合并后的数据
$mergedData | Export-Csv -NoTypeInformation -Encoding utf8 $historyFilePath

脚本说明

  • 解析新数据时,将votecount转为整数,并标记本期是否达标
  • 读取历史数据时,解析已有的累计票数和达标次数(兼容25D或50D2格式)
  • 合并时自动累加票数和达标次数,新用户直接初始化数据
  • 输出格式优化:达标1次显示XD,多次显示XDn,未达标仅显示票数

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 16:10:33