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

如何用任务计划程序在登录时后台运行PowerShell脚本

问题描述

目标

通过PowerShell创建计划任务,使PowerShell脚本无可见窗口、无提示、无用户交互地在后台运行。

实际问题

编写的计划任务创建代码,在注销重新登录后脚本无法运行;此前手动在任务计划程序执行时,脚本能正常运行但会弹出窗口,目前窗口问题已解决。

代码说明

1. AddTasks函数

function addTasks {
    param(
        [Parameter()]
        [string]$softwareDirectory,
        [Parameter()]
        [string]$imagesDirectory
    )

    functionPresentation -text "Adding Tasks"

    $taskTrigger = New-ScheduledTaskTrigger -AtLogOn

    $wallpaperTask = New-ScheduledTaskAction -Execute "Powershell.exe" -Argument "-NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File $softwareDirectory\changeWallpaper.ps1"
    Register-ScheduledTask -TaskName "Change Wallpaper" -TaskPath "FuckHugo" -Action $wallpaperTask -Trigger -RunLevel Highest -Force
}

该函数用于添加计划任务,后续会扩展添加更多同要求任务。

2. changeWallpaper.ps1

function detectAppropriatedImages {
    param (
        [string]$imagesDirectory
    )

    Add-Type -AssemblyName System.Drawing

    $images = Get-ChildItem -Path $imagesDirectory -File -Filter *.jpg
    $fileList = $images.FullName
    [System.Collections.ArrayList]$appropriateImages = @()

    foreach ($image in $fileList) {
        $loadedImage = [System.Drawing.Image]::FromFile($image)

        if ($($loadedImage.Width) -ge 1920 -and $($loadedImage.Height) -ge 1080) {
            $appropriateImages += ($image)
        }

        $loadedImage.Dispose()
    }

    return $appropriateImages
}


$imagesDirectory = "C:\Windows\Media\Garden\Wallpapers\Images"
$wallpapers = detectAppropriatedImages -imagesDirectory $imagesDirectory
$wallpaperCode = @' 
        using System.Runtime.InteropServices; 
        namespace Win32 { 
            public class Wallpaper { 
                [DllImport("user32.dll", CharSet=CharSet.Auto)] 
                static extern int SystemParametersInfo (int uAction, int uParam, string lpvParam, int fuWinIni); 
        
                public static void SetWallpaper(string path) { 
                    SystemParametersInfo(20,0,path,3); 
                }
            }
        }
'@
Add-Type $wallpaperCode

while ($true) {
    $randomImage = $($wallpapers | Get-Random)
    [Win32.Wallpaper]::SetWallpaper($randomImage)
    Start-Sleep -Seconds 10
}

该脚本筛选分辨率≥1920×1080的图片,每10秒随机设置为壁纸。


解决方案

1. 修复计划任务注册语法错误

当前Register-ScheduledTask命令中,-Trigger参数未传入定义好的$taskTrigger变量,导致登录触发器未正确绑定,这是登录后任务不运行的核心问题。同时为脚本路径添加双引号,避免路径含空格时解析失败。修改后的函数如下:

function addTasks {
    param(
        [Parameter()]
        [string]$softwareDirectory,
        [Parameter()]
        [string]$imagesDirectory
    )

    functionPresentation -text "Adding Tasks"

    $taskTrigger = New-ScheduledTaskTrigger -AtLogOn

    $wallpaperTask = New-ScheduledTaskAction -Execute "Powershell.exe" -Argument "-NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File `"$softwareDirectory\changeWallpaper.ps1`""
    Register-ScheduledTask -TaskName "Change Wallpaper" -TaskPath "FuckHugo" -Action $wallpaperTask -Trigger $taskTrigger -RunLevel Highest -Force
}

2. 配置任务权限与运行策略

打开任务计划程序,找到FuckHugo路径下的Change Wallpaper任务,进入属性设置:

  • 常规选项卡:勾选“不管用户是否登录都要运行”,若脚本无需管理员权限,取消勾选“使用最高权限运行”(避免权限冲突);若必须最高权限,确认当前用户账户拥有对应权限。
  • 设置选项卡:取消勾选“如果运行时间超过X小时就停止任务”,勾选“允许任务按需运行”,同时可设置“任务失败后重试间隔”(如5分钟)。

3. 优化脚本稳定性

由于changeWallpaper.ps1是无限循环脚本,添加错误处理避免非致命错误终止运行:
在脚本开头添加:

$ErrorActionPreference = 'SilentlyContinue'

4. 验证任务状态

  • 登录后查看任务计划程序中任务的“上次运行结果”,显示“操作成功完成 (0x0)”则说明任务正常启动。
  • 打开任务管理器“详细信息”标签,确认对应的powershell.exe进程是否在运行。

内容的提问来源于stack exchange,提问作者jefrey hernandez rodriguez

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 19:31:00