Passing Parameters to powershell script in scheduled task - windows

I am trying to create a scheduled task that will run a Powershell script with 1 parameter - this is on Server 2012 with Powershell v5 installed. So far I have been able to get the task to run, but it doesn't recognize my param value - the value is null in my script that I am calling. Here is what I have to create the scheduled task:
$TicketTime = "9:00pm"
$EmpID = "1234"
$Firstname = "Test"
$Lastname = "User"
$Action = New-ScheduledTaskAction -Execute "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -Argument "-ExecutionPolicy ByPass -File C:\Scripts\Term.ps1 -EmpID '$EmpID'"
$Trigger = New-ScheduledTaskTrigger -Once -At "03/29/2016 $TicketTime"
$Task = New-ScheduledTask -Action $Action -Trigger $Trigger -Settings (New-ScheduledTaskSettingsSet)
$Task | Register-ScheduledTask -TaskName "$Firstname $Lastname" -User "myuser" -Password "mypass"
This will execute successfully, but will not recognize the -EmpID parameter. I have also tried -Command instead of -File for the Argument value but I get the same result.
-ExecutionPolicy ByPass -Command "& C:\Scripts\Term.ps1 -EmpID 1234"
Single quotes around the param doesn't seem to do anything either
-ExecutionPolicy ByPass -Command "& C:\Scripts\Term.ps1 -EmpID '1234'"
So far nothing I do will get the param to pass. What am I missing?

Can you try and declare your parameters as positional rather than named:
[CmdletBinding()]
Param (
[Parameter(Position=0)]
[string]$Ticket
)
"-ExecutionPolicy ByPass -File C:\Scripts\Term.ps1 '$EmpID'"
Then you can drop the -ParamName and pass it in using position.

You can use the -File option, you just need to separate out the string:
Change
-ExecutionPolicy ByPass -File "& C:\Scripts\Term.ps1 -EmpID 1234"
to
-ExecutionPolicy ByPass -File "C:\Scripts\Term.ps1" -EmpID "1234"
The full string out look like this:
$Action = New-ScheduledTaskAction -Execute "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -Argument "-ExecutionPolicy ByPass -File `"C:\Scripts\Term.ps1`" -EmpID `"$EmpID`""

Related

Cannot register scheduled task for creating system restore points using Powershell

I am trying to automate creation of system restore points using Powershell (v7.2.6). Following are the commands that I have run:
$action = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument 'ExecutionPolicy Bypass -Command "Checkpoint-Computer -Description \"Auto Backup\" -RestorePointType \"MODIFY_SETTINGS\""'
$trigger = New-ScheduledTaskTrigger -Weekly -At 9am
$stsettings = New-ScheduledTaskSettingsSet -DontStopIfGoingOnBatteries -StartWhenAvailable
These work fine but when I run...
Register-ScheduledTask -TaskName "Auto System Backup" -RunLevel Highest -Action $action -Trigger $trigger -Settings $stsettings
...I get the an error message: Register-ScheduledTask: The parameter is incorrect.
Not sure which parameter is incorrect though. What am I doing wrong here?
The below command is wrong. There is no -Monthly parameter in New-ScheduledTaskTrigger. Also what you have specified does not make sense, Monthly 9am??
$trigger = New-ScheduledTaskTrigger -Monthly -At 9am

Process runs in Powershell Prompt but not as a scheduled task?

$taskTrigger1 = New-ScheduledTaskTrigger -Once -At 2:50PM
$taskAction = New-ScheduledTaskAction `
-Execute "powershell.exe" `
-Argument "-ExecutionPolicy ByPass -File `"<path>\tiddlywikiIIS_schtask_rsync\backup.ps1`""
$taskName = "Backup Stuff"
$description = "Rsync Backup Stuff"
Register-ScheduledTask `
-TaskName $taskName `
-Action $taskAction `
-Trigger $taskTrigger1 `
-Description $description
$taskPrinciple = New-ScheduledTaskPrincipal -UserId "Domain\someadmin" -RunLevel Highest
$taskSettings = New-ScheduledTaskSettingsSet -Compatibility Win8
Set-ScheduledTask -TaskName $taskName -Principal $taskPrinciple -Settings $taskSettings
Set-ScheduledTask -TaskName $taskName -User $taskPrinciple.UserID -Password '******'
# Pull the creds for a user account that has WSL installed on it.
$cred = Get-StoredCredential -Target "some-non-admin-credz"
$psi = New-Object System.Diagnostics.ProcessStartInfo -Property #{
RedirectStandardError = $true
RedirectStandardOutput = $true
UseShellExecute = $False
UserName = $cred.GetNetworkCredential().Username
Domain = $cred.GetNetworkCredential().Domain
Password = $cred.Password
WorkingDirectory = "C:\windows\"
FileName = "wsl"
Arguments = "-d Ubuntu-18.04 -e rsync -av --delete /mnt/c/stuff/ /mnt/o/stuff_bk/"
WindowStyle = "Hidden"
}
$p = New-Object System.Diagnostics.Process
$p.StartInfo = $psi
$p.WaitForExit()
$p.ExitCode
backup.ps1
I have the code above running in a scheduled task that is running with an (domain?) administrator account.
When it returns from the scheduled task it's $p.ExitCode is -1073741502 but if I run the same code in an administrative powershell prompt run as the same (domain?) administrative account it runs fine.
It makes me thing that it has something to do with the Local Security Policy as I remember there being some sort of "Allow Batch Execution" or "Delegate" or some such privilege in there that prevents any group or user not included from running something as a batch job.
I also found the following log in the Event Viewer:
Okay, so I found a log entry in the System Log with a Source of Application Popup, Event ID 26 which reads:
EventData -> Caption: `wsl.exe - Application Error`
EventData -> Message: `The application was unable to start correctly (0xc0000142). Click OK to close the application.`

Powershell: Task every minute

I run the following command in PowerShell:
Schtasks /create /tn "Scheduler Test4" /sc minute /tr "PowerShell -command cp c:\Users\myUsername\Desktop\myCat/main.txt c:/Users/myUsername/Desktop/myCat_backup/"
It doesn't work. I desire that main.txt gets copied into the backup directory. When I look in myCat_backup/ there is no main.txt, even if I remove the -command flag. Please help.
This script will create a sheduled task that runs powershell every minute as the user "System":
$Action = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument '-NonInteractive -NoLogo -NoProfile -command Copy-Item C:\temp\Source\main.txt C:\temp\Target\'
$trigger = New-ScheduledTaskTrigger -Once -At (Get-Date) -RepetitionInterval (New-TimeSpan -Minutes 1)
$Settings = New-ScheduledTaskSettingsSet
$Task = New-ScheduledTask -Action $Action -Trigger $Trigger -Settings $Settings
Register-ScheduledTask -TaskName 'Scheduler Test' -InputObject $Task -User 'system'
It turns out once I restarted my device, the script started working. Furthermore, I can now create more tasks and Powershell is recognizing the commands created using Schtasks without restarting.

Cannot process argument transformation on parameter 'Principal'. Cannot convert value "" to type "Microsoft.Management.Infrastructure.CimInstance"

I am trying to create a scheduled task in Powershell which will run a job that uses the active desktop.
1) is my assumption correct that a scheduled task can see the active desktop when it runs?
2) When I execute the following poweshell script, I keep getting an error: Cannot process argument transformation on parameter 'Principal'. Cannot convert value "Servername" to type "Microsoft.Management.Infrastructure.CimInstance"
The code is below:
import-module PSScheduledjob
$TaskStartTime = (Get-Date).AddMinutes(2)
$TaskName = "ExecTestCase"
write-output $TaskStartTime
$action = New-ScheduledTaskAction -Execute "C:\Selenium_Ruby\framework\run_locally_but_update_from_PROD_first.bat"
$trigger = New-ScheduledTaskTrigger -At $TaskStartTime -Once
$principal = "servername\userid" #assume servername \ userid is in quotes
Register-ScheduledTask BatchRunTask -action $action -principal $principal -trigger $trigger
What is wrong?
Also sometimes I get an access denied for the scheduled task too
thanks
The parameter -principal does not accept string input.
Refer to this documentation.
Example:
$STPrin = New-ScheduledTaskPrincipal -GroupId "BUILTIN\Administrators" -RunLevel Highest

What is the switch in Windows schtasks for ExecutionTimeLimit in the xml file?

Windows schtasks.exe:
What is the equivalent command line switch for ExecutionTimeLimit in schtasks. In the Edit Tasks dialog it is "Stop tasks if it runs longer than".
I tried /ET end time and /DU duration but they imply a repetition. I only want a task to run once and then be killed x minutes later.
Not a perfect solution , but you can use /XML option of schtasks
schtasks /Create /tn jobname /XML Path_of_xml
Within the xml file you should able to use ExecutionTimeLimit to specify the time you want to kill the job .
You can get sample xml by export a exist job to get reference
schtasks /Query /tn jobname /XML > Path_of_xml
Using the Powershell it is possible to create a task where you can modify ExecutionTimeLimit to your value.
$MyPathToFile = 'C:\Path\File.exe'
$hour = '20:00:00'
$user = 'MyDomain\MyUserName'
$password = '123321Password'
$MyTask = 'MyTask'
$MyExecutionTimeLimit = '01:00:00' # HH:MM:SS
$trigger = New-ScheduledTaskTrigger -Daily -At $hour
$action = New-ScheduledTaskAction -Execute $MyPathToFile
$settingsSet = New-ScheduledTaskSettingsSet -ExecutionTimeLimit $MyExecutionTimeLimit
$task = New-ScheduledTask -Action $action -Trigger $trigger -Settings $settingsSet
Register-ScheduledTask -TaskName $MyTask -InputObject $task -User $user -Password $password

Resources