# 设置控制台编码 [Console]::OutputEncoding = [System.Text.Encoding]::UTF8 [Console]::InputEncoding = [System.Text.Encoding]::UTF8 $OutputEncoding = [System.Text.Encoding]::UTF8 # 获取当前目录的完整路径 $currentPath = Split-Path -Parent -Path $MyInvocation.MyCommand.Definition $scriptPath = Join-Path $currentPath "run-tests.bat" $currentUser = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name # Task Configuration $taskNamePrefix = "Playwright_AutoTest" $taskDesc = "Run Playwright tests daily" function Show-Menu { Clear-Host Write-Host "`n================== Playwright Test Manager ==================`n" Write-Host "1. View All Tasks Status" Write-Host "2. Set Daily Task - DEV Environment (Default: 23:00)" Write-Host "3. Set Daily Task - UAT Environment" Write-Host "4. Run Test Now" Write-Host "5. Delete Tasks" Write-Host "Q. Exit" Write-Host "`nEnter your choice (1-5, or Q to exit): " -NoNewline } function Get-TaskStatus { $environments = @("Dev", "UAT") $found = $false Write-Host "`nTasks Status:" foreach ($env in $environments) { $taskName = "${taskNamePrefix}_$env" $task = Get-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue if ($task) { $found = $true Write-Host "`n$env Environment Task:" Write-Host "Name: $taskName" Write-Host "State: $($task.State)" # 获取更详细的任务信息 $taskInfo = Get-ScheduledTaskInfo -TaskName $taskName -ErrorAction SilentlyContinue $trigger = $task.Triggers[0] if ($trigger) { Write-Host "Schedule: Daily at $($trigger.StartBoundary.Split('T')[1].Substring(0,5))" if ($taskInfo -and $taskInfo.NextRunTime) { Write-Host "Next Run: $($taskInfo.NextRunTime.ToString('yyyy-MM-dd HH:mm'))" } else { Write-Host "Next Run: Task needs to be enabled" } } Write-Host "Last Result: $($task.LastTaskResult)" Write-Host "Working Directory: $($task.Actions[0].WorkingDirectory)" Write-Host "Run As User: $($task.Principal.UserId)" } } if (-not $found) { Write-Host "`nNo tasks found. Please set up tasks using options 2 or 3." } Pause-Script } function Set-DailyTask { param ( [string]$runTime = "23:00", [string]$environment ) $taskName = "${taskNamePrefix}_$environment" Write-Host "`nSetting up daily task for $environment environment..." $scriptPath = Join-Path $PSScriptRoot "run-tests.bat" if (-not (Test-Path $scriptPath)) { Write-Host "`nError: Test script not found at: $scriptPath" Write-Host "Path: $scriptPath" Pause-Script return } # 确保时间格式正确 if ($runTime -notmatch "^([01]?[0-9]|2[0-3]):[0-5][0-9]$") { Write-Host "`nError: Invalid time format. Please use HH:mm format (e.g., 23:00)" Pause-Script return } try { # 创建任务操作 - 添加环境参数 $envArg = $environment.ToLower() $action = New-ScheduledTaskAction -Execute $scriptPath -WorkingDirectory $PSScriptRoot -Argument $envArg if (-not $action) { throw "Failed to create task action" } # 创建任务触发器 $trigger = New-ScheduledTaskTrigger -Daily -At $runTime if (-not $trigger) { throw "Failed to create task trigger" } # 创建任务设置 $settings = New-ScheduledTaskSettingsSet ` -RestartCount 3 ` -RestartInterval (New-TimeSpan -Minutes 5) ` -StartWhenAvailable ` -DontStopOnIdleEnd ` -ExecutionTimeLimit (New-TimeSpan -Hours 2) if (-not $settings) { throw "Failed to create task settings" } # 创建任务主体 $principal = New-ScheduledTaskPrincipal -UserId $currentUser -RunLevel Highest if (-not $principal) { throw "Failed to create task principal" } $existingTask = Get-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue if ($existingTask) { # 更新现有任务 $result = Set-ScheduledTask -TaskName $taskName ` -Action $action ` -Trigger $trigger ` -Settings $settings ` -Principal $principal if ($result) { Write-Host "`nTask successfully updated!" } else { throw "Failed to update task" } } else { # 创建新任务 $result = Register-ScheduledTask -TaskName $taskName ` -Description "$taskDesc ($environment Environment)" ` -Action $action ` -Trigger $trigger ` -Settings $settings ` -Principal $principal if ($result) { Write-Host "`nTask successfully created!" } else { throw "Failed to create task" } } # 验证任务创建/更新是否成功 $updatedTask = Get-ScheduledTask -TaskName $taskName -ErrorAction Stop if ($updatedTask) { Write-Host "`nTask Details:" Write-Host "Task Name: $taskName" Write-Host "Environment: $environment" Write-Host "Run Time: Daily at $runTime" if ($updatedTask.NextRunTime) { Write-Host "Next Run: $($updatedTask.NextRunTime.ToString('yyyy-MM-dd HH:mm'))" } else { Write-Host "Next Run: Not scheduled" } Write-Host "Status: $($updatedTask.State)" Write-Host "Run As: $($updatedTask.Principal.UserId)" } else { Write-Host "`nWarning: Task was created but could not be verified." } } catch { Write-Host "`nError setting up task: $_" Write-Host "Please make sure you have administrative privileges." Write-Host "Error details: $($_.Exception.Message)" } Pause-Script } function Update-TaskTime { Write-Host "`nSelect environment:" Write-Host "1. Development (dev)" Write-Host "2. UAT" Write-Host "`nEnter your choice (1-2): " -NoNewline $envChoice = Read-Host $environment = switch ($envChoice) { "1" { "dev" } "2" { "uat" } default { Write-Host "`nInvalid choice. Using default (dev)" "dev" } } Write-Host "`nEnter new time (HH:mm, e.g. 02:00): " -NoNewline $newTime = Read-Host if ($newTime -match "^([01]?[0-9]|2[0-3]):[0-5][0-9]$") { Set-DailyTask -runTime $newTime -environment $environment } else { Write-Host "`nInvalid time format" Pause-Script } } function Start-TestNow { Write-Host "`nSelect environment:" Write-Host "1. Development (dev)" Write-Host "2. UAT" Write-Host "`nEnter your choice (1-2): " -NoNewline $envChoice = Read-Host $env = switch ($envChoice) { "1" { "dev" } "2" { "uat" } default { Write-Host "`nInvalid choice. Using default (dev)" "dev" } } Write-Host "`nStarting test in $env environment..." try { $scriptPath = Join-Path $PSScriptRoot "run-tests.bat" # 使用cmd直接运行,这样可以看到实时输出 & cmd /c $scriptPath $env Write-Host "`nTest completed" } catch { Write-Host "`nError: $_" } Pause-Script } function Remove-AutomationTask { Write-Host "`nSelect tasks to delete:" Write-Host "1. DEV Environment Task" Write-Host "2. UAT Environment Task" Write-Host "3. Both Tasks" Write-Host "`nEnter your choice (1-3): " -NoNewline $choice = Read-Host $tasksToDelete = switch ($choice) { "1" { @("Dev") } "2" { @("UAT") } "3" { @("Dev", "UAT") } default { Write-Host "`nInvalid choice." Pause-Script return } } foreach ($env in $tasksToDelete) { $taskName = "${taskNamePrefix}_$env" $task = Get-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue if ($task) { try { Unregister-ScheduledTask -TaskName $taskName -Confirm:$false Write-Host "`nTask '$taskName' deleted" } catch { Write-Host "`nError deleting task '$taskName': $_" } } else { Write-Host "`nTask '$taskName' not found" } } Pause-Script } function Pause-Script { Write-Host "`nPress Enter to continue..." -NoNewline Read-Host } # Main Loop do { Show-Menu $choice = Read-Host switch ($choice.ToUpper()) { "1" { Get-TaskStatus } "2" { Set-DailyTask -environment "Dev" } "3" { Write-Host "`nEnter time for UAT task (HH:mm, e.g. 02:00): " -NoNewline $uatTime = Read-Host if ($uatTime -match "^([01]?[0-9]|2[0-3]):[0-5][0-9]$") { Set-DailyTask -runTime $uatTime -environment "UAT" } else { Write-Host "`nInvalid time format" Pause-Script } } "4" { Start-TestNow } "5" { Remove-AutomationTask } "Q" { exit } default { Write-Host "`nInvalid choice. Please try again." Pause-Script } } } while ($true)