简体   繁体   English

Powershell - 创建计划任务以作为本地系统/服务运行

[英]Powershell - Create Scheduled Task to run as local system / service

Can anyone tell me how to create a scheduled task using powershell that runs as the local system or local service?谁能告诉我如何使用作为本地系统或本地服务运行的 powershell 创建计划任务?

Everything works great except the call to ITaskFolder.RegisterTaskDefinition().除了调用 ITaskFolder.RegisterTaskDefinition() 之外,一切都很好。

If I pass in $null, or "", than the call bombs saying invalid username or password.如果我传入 $null 或“”,则呼叫炸弹会说无效的用户名或密码。 Any thoughts"任何想法”

$Rootfolder.RegisterTaskDefinition("Test", $Taskdef, 6, "LOCAL SERVICE", "", 3) $Rootfolder.RegisterTaskDefinition("Test", $Taskdef, 6, "LOCAL SERVICE", "", 3)

For those who can use PowerShell 3.0 on Windows 8 or Windows Server 2012 , new cmdlets will let you do it in a simple way when registering your scheduled task with the cmdlet Register-ScheduledTask and as argument -User "System"对于那些可以在Windows 8 或 Windows Server 2012上使用PowerShell 3.0 的人,新的 cmdlet 将让您在使用 cmdlet Register-ScheduledTask注册计划任务并作为参数-User "System"时以简单的方式执行此操作

Here is a scheduled task created entirely with PS, its purpose is to restart a service My Service, using the SYSTEM account, 3 minutes after the system has started:这是一个完全用PS创建的计划任务,其目的是在系统启动3分钟后使用SYSTEM帐户重新启动服务My Service:

$taskname = "Restart My Service"
$taskdescription = "Restart My Service after startup"
$action = New-ScheduledTaskAction -Execute 'Powershell.exe' `
  -Argument '-NoProfile -WindowStyle Hidden -command "& Restart-Service -displayname \"My Service\""'
$trigger =  New-ScheduledTaskTrigger -AtStartup -RandomDelay (New-TimeSpan -minutes 3)
$settings = New-ScheduledTaskSettingsSet -ExecutionTimeLimit (New-TimeSpan -Minutes 2) -RestartCount 3 -RestartInterval (New-TimeSpan -Minutes 1)
Register-ScheduledTask -Action $action -Trigger $trigger -TaskName $taskname -Description $taskdescription -Settings $settings -User "System"

NB: you will need to run powershell as an administrator for that script.注意:您需要以该脚本的管理员身份运行 powershell。

This code snippet will use the PowerShellPack 's Task Scheduler module to schedule a task to run as SYSTEM immediately:此代码片段将使用PowerShellPack的 Task Scheduler 模块来安排任务立即以 SYSTEM 身份运行:

New-Task |
    ForEach-Object {
        $_.Principal.Id = "NTAuthority\SYSTEM"
        $_.Principal.RunLevel = 1
        $_
    } |
    Add-TaskAction -Script {
        "SystemTask" > C:\myTest.txt
    } |
    Add-TaskTrigger -OnRegistration |
    Register-ScheduledTask SystemTask

I think you would need to use "nt authority\\localservice" as the user name.我认为您需要使用“nt authority\\localservice”作为用户名。

Kindness,善良,

Dan

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM