PS: Scheduled task

Hi,

I have a PS script which sets a PS scheduled task BUT it lacks some things = setting username to run with + 'run whether user is logged on or not', configure task for Windows 2012 R2 instead of default ".

Can't figure out howto do this in Powershell.

Please advise.

This is the script:


 
function new-PSScheduledTask
{

  param(

    [Parameter(Mandatory = $true)][string[] $Computername,      
    [Parameter(Mandatory = $true)][string] $ScriptPath,
    [Parameter(Mandatory = $true)][string]$FunctiontoExecute,
    [Parameter(Mandatory = $true)][string]$Taskname,
    [Parameter(Mandatory = $false)]$TriggerTime = '6:00'  
  )
 
    invoke-command -ScriptBlock {
   
      $TriggerFrequency = @{ Daily = $true }
      $Trigger = New-ScheduledTaskTrigger -At $using:TriggerTime @TriggerFrequency
 
      $commandtoexecute = "& {. $using:ScriptPath;$using:functiontoexecute}"
      $argument = "-NoProfile -WindowStyle Hidden -command $commandtoexecute"
     
      $action = New-ScheduledTaskAction -Execute 'Powershell.exe' -Argument $argument
      Register-ScheduledTask -Action $action -Trigger $trigger -TaskName $using:TaskName -Description $using:TaskName  -RunLevel Highest #-User $UsernameTorunScheduledJob
    } -ComputerName $Computername
   
    Write-Output "TO SET: username to run with + 'run whether user is logged on or not', configure for Windows 2012 R2 "
}
janhoedtAsked:
Who is Participating?
 
Jose Gabriel Ortega CEE Solution Guide - CEO Faru Bonon ITCommented:
function new-PSScheduledTask{
    [Cmdletbinding()]
    param( 
        [Parameter(Mandatory = $true,Position=0)][string[] $Computername,      
        [Parameter(Mandatory = $true,Position=1)][string] $ScriptPath,
        [Parameter(Mandatory = $true,Position=2)][string]$FunctiontoExecute, 
        [Parameter(Mandatory = $true,Position=3)][string]$Taskname,
        [Parameter(Mandatory = $true,Position=4)][string]$UserName="$($env:USERDOMAIN)\$($env:USERNAME)",
        [Parameter(Mandatory = $true,Position=5)][string]$Password="pwd",
        [Parameter(Mandatory = $false,Position=6)]$TriggerTime = '6:00'  
    )
  
    invoke-command -ScriptBlock {
    #$action = New-ScheduledTaskAction -Execute foo.exe -Argument "bar baz"
    $principal = New-ScheduledTaskPrincipal -UserId $UserName -LogonType ServiceAccount -RunLevel Highest
    $settings = New-ScheduledTaskSettingsSet -MultipleInstances Parallel 

    $TriggerFrequency = @{ Daily = $true }
    $Trigger = New-ScheduledTaskTrigger -At $using:TriggerTime @TriggerFrequency 
  
    $commandtoexecute = "& {. $using:ScriptPath;$using:functiontoexecute}"
    $argument = "-NoProfile -WindowStyle Hidden -command $commandtoexecute"
      
    $action = New-ScheduledTaskAction -Execute 'Powershell.exe' -Argument $argument
    Register-ScheduledTask -Action $action -Trigger $trigger -TaskName $using:TaskName -Description $using:TaskName  -RunLevel Highest -Principal $UserName -Settings $settings -Password $pwd 
    Write-Output "TO SET: username to run with + 'run whether user is logged on or not', configure for Windows 2012 R2 "
    } -ComputerName $Computername
}

Open in new window


This is untested and here's a couple of wikis from me:

https://social.technet.microsoft.com/wiki/contents/articles/46768.how-to-run-a-powershell-script-with-parameters.aspx

https://social.technet.microsoft.com/wiki/contents/articles/38580.configure-to-run-a-powershell-script-into-task-scheduler.aspx
0
 
Panagiotis ToumpaniarisSystem EngineerCommented:
To run the task as a specific user, use New-ScheduledTaskPrincipal.

I believe that if you save the password, the task will run whether the user is logged in or not.
0
 
janhoedtAuthor Commented:
Does not work
Cannot validate argument on parameter 'UserId'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.

Command is
 new-PSScheduledTask -Computername servername -ScriptPath 'e:\myscript.pst' -FunctiontoExecute 'Get-something' -Taskname 'sometask'

then it prompts for user and password but it throws an error.
0
Simplify Active Directory Administration

Administration of Active Directory does not have to be hard.  Too often what should be a simple task is made more difficult than it needs to be.The solution?  Hyena from SystemTools Software.  With ease-of-use as well as powerful importing and bulk updating capabilities.

 
Jose Gabriel Ortega CEE Solution Guide - CEO Faru Bonon ITCommented:
Post the error you're getting?
0
 
janhoedtAuthor Commented:
Error is

Cannot validate argument on parameter 'UserId'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.
0
 
Jose Gabriel Ortega CEE Solution Guide - CEO Faru Bonon ITCommented:
Well this example works:
$action = New-ScheduledTaskAction -Execute 'Powershell.exe' -Argument '-NoProfile -WindowStyle Hidden -command "& {get-eventlog -logname Application -After ((get-date).AddDays(-1)) | Export-Csv -Path c:\Reports\applog.csv -Force -NoTypeInformation}"'
$trigger =  New-ScheduledTaskTrigger -Daily -At 11am
Register-ScheduledTask -Action $action -Trigger $trigger -TaskName "AppLog" -Description "Daily dump of Applog"

Open in new window

here's the source: https://social.technet.microsoft.com/Forums/lync/en-US/d87da3b2-ea3b-4b68-82f4-be0bf685446b/powershell-to-create-schedule-task-on-windows-10?forum=winserverpowershell

So It should be related to the task itself, so the error should be within the Scriptblock:
#$action = New-ScheduledTaskAction -Execute foo.exe -Argument "bar baz"
    $principal = New-ScheduledTaskPrincipal -UserId $UserName -LogonType ServiceAccount -RunLevel Highest
    $settings = New-ScheduledTaskSettingsSet -MultipleInstances Parallel 

    $TriggerFrequency = @{ Daily = $true }
    $Trigger = New-ScheduledTaskTrigger -At $using:TriggerTime @TriggerFrequency 
  
    $commandtoexecute = "& {. $using:ScriptPath;$using:functiontoexecute}"
    $argument = "-NoProfile -WindowStyle Hidden -command $commandtoexecute"
      
    $action = New-ScheduledTaskAction -Execute 'Powershell.exe' -Argument $argument
    Register-ScheduledTask -Action $action -Trigger $trigger -TaskName $using:TaskName -Description $using:TaskName  -RunLevel Highest -Principal $UserName -Settings $settings -Password $pwd 

Open in new window

Will check it later.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.