无法使用具有选项 "run only when user is logged on" 的 powershell 创建计划任务



>有谁知道如何创建一个脚本,使我能够设置选项仅在用户登录时运行?我已经搜索了几个小时,但没有找到好的解决方案。问题是该程序无法在后台运行,因此,据我所知,必须仅在用户登录时运行。任何建议都值得赞赏

$taskName = 'task name'
$taskDescription = 'task desc'
$executable = "program.exe"
$workingDir = "C:utv"
$user = "user"
$password = "password"
Write-Host "Configuring scheduled task"
Write-Host " - Executable: $workingDir$executable"
Write-Host " - User: $user"
Write-Host "pw: $password"
$action = New-ScheduledTaskAction -Execute "$workingDir$executable"
$trigger = New-ScheduledTaskTrigger -Daily -At 00:01 
$existingTask = Get-ScheduledTask | Where-Object {$_.TaskName -like     $taskName}
$principal = New-ScheduledTaskPrincipal -UserId $user
if ($existingTask) {
Write-Host "Existing task found, updating..."
Set-ScheduledTask `
-TaskName $taskName  `
-Action $action `
-Trigger $trigger -User $user -Password $password
}
else {
Write-Host "Creating new task..."
Register-ScheduledTask `
-TaskName $taskName `
-Description $taskDescription `
-Action $action `
-Trigger $trigger -User $user -Password $password
}
Write-Host "Setting Repetition properties"
$newTask = Get-ScheduledTask | Where-Object {$_.TaskName -like $taskName}
$newTask.Triggers.repetition.Duration = 'PT23H'
$newTask.Triggers.repetition.Interval = 'PT60M'
$newTask.Principal.LogonType = 
$newTask | Set-ScheduledTask -User $user -Password $password
Write-Host "Done!"

您的脚本似乎缺少一些参数。

$newTask.Principal.LogonType = 

将此值设置为 S4U 应选择"无论用户是否登录都运行",但它可能会设置"不存储密码..."勾选其下方的复选框。使用 -User 或 -Password 参数调用 Register-ScheduledTask 时,应默认为所需的输出,因此不需要 New-ScheduledTaskPrincipal,或者可能不需要编辑任务 Principal.LogonType。

此外,在注册计划任务上使用 -User 和 -Password 参数时,HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa\disabledomaincreds必须设置为 0 和 secpol.msc,并且必须将用户添加到secpol.msc>本地安全策略>用户权限分配>作为服务登录

无需设置"用户登录时运行",因为这是默认设置。

我正在寻找相同的解决方案,并通过我收到的错误发现了它:Parameter set cannot be resolved using the specified name parameters.

这基本上意味着您必须查看 Set-ScheduledTask 的语法段落,并检查允许哪些参数。 如果使用New-ScheduledTaskPrincipal并将主体注册到计划任务,则会注意到不允许使用-User-Password

Set-ScheduledTask
[[-Principal] <CimInstance>]
[[-Action] <CimInstance[]>]
[[-TaskPath] <String>]
[[-Settings] <CimInstance>]
[[-Trigger] <CimInstance[]>]
[-TaskName] <String>
[-CimSession <CimSession[]>]
[-ThrottleLimit <Int32>]
[-AsJob]
[<CommonParameters>]

确保为New-ScheduledTaskPrincipal设置-LogonType(如交互式)和-RunLevel。 我找到了这个 Principal.LogonType 属性的 Windows 开发人员链接,它比 PowerShell 的更好地解释了-LogonType

相关内容

最新更新