如何在前台运行 Windows 任务?

问题描述 投票:0回答:3

我有一个任务无法正常工作,我希望它在前台运行,以便我可以看到它的进度。我的任务是一个 powershell 脚本,当我手动运行它时它工作得很好,但是当任务运行它时,某些部分会失败。

谢谢!

powershell scheduled-tasks task
3个回答
4
投票

您可以尝试使用Start-Transcript。这会将所有输出捕获到文本文件中。


0
投票

您没有说明您的操作系统,按钮的确切位置会根据操作系统而变化。

对于 Windows 7 / 2008 R2:

双击该任务。在任务窗口中选中“不存储密码”旁边的复选框,然后单击“确定”。右键单击该任务并选择运行。


0
投票

下面是一个完整的独立工作示例 Powershell 脚本,它启动一个计划任务,该任务显示为前台控制台窗口。该脚本创建一个计划任务,该任务每分钟运行相同的示例脚本。它在 Windows 10、Windows 11 的 Powershell 版本 5.1 中运行良好。

此方法的优点是可以完全以编程方式创建计划任务,无需手动在任务计划程序应用程序中进行任何更改。

这个脚本最重要的命令是

schtasks /create
有关此命令的许多有趣信息以及许多示例可以在下面的网站中找到 https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/schtasks-create

例如,使用下面的命令将启动一个计划任务,该任务每周仅在周五、周六和周日的 22:00(晚上 10:00)运行,而不是像脚本中那样每分钟运行一次。

schtasks /create /tn $scheduled_task_name /sc weekly /st 22:00 /d FRI,SAT,SUN /rl 'Highest' /tr $scheduled_task_command;

在此示例脚本中,计划任务通过选项

/rl 'Highest'
设置为具有提升的管理员权限,这对于运行一些需要管理员权限的计划任务非常有用。要在没有管理员权限的情况下运行计划任务,可以使用
/rl 'Limited'
选项,这是默认选项。

-NoExit
参数使控制台窗口在任务完成所有指令后不会退出。如果任务完成所有指令后控制台窗口必须消失,则可以删除此参数。

[string] $script_path = $MyInvocation.MyCommand.Definition; # extract the full path and name of this script
[string] $scheduled_task_name = "ScheduledTask";
#[string] $powershell_executable = "C:\WINDOWS\system32\WindowsPowerShell\v1.0\Powershell.exe"; # full path to Powershell executable
[string] $powershell_executable = "Powershell.exe";
[string] $parameter_list = " -NoLogo -NoExit -ExecutionPolicy Bypass -File `'" + $script_path + "`'";
[string] $scheduled_task_command = $powershell_executable + $parameter_list;
$scheduled_task_exists = $null;

$scheduled_task_exists = Get-ScheduledTask -ErrorAction SilentlyContinue | Where-Object {$_.TaskName -ceq $scheduled_task_name };

if(-not ($scheduled_task_exists)) {
    schtasks /create /tn $scheduled_task_name /sc minute /mo 1 /rl 'Highest' /tr $scheduled_task_command;
}

Write-Host "Foreground scheduled task script output"
© www.soinside.com 2019 - 2024. All rights reserved.