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?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

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
Jose Gabriel Ortega CastroCEOCommented:
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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
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
Discover the Answer to Productive IT

Discover app within WatchGuard's Wi-Fi Cloud helps you optimize W-Fi user experience with the most complete set of visibility, troubleshooting, and network health features. Quickly pinpointing network problems will lead to more happy users and most importantly, productive IT.

Jose Gabriel Ortega CastroCEOCommented:
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 CastroCEOCommented:
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
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Powershell

From novice to tech pro — start learning today.