Scheduled powershell script invoke-expression not calling another script - powershell

I want to schedule a powershell script. It's okay but the powershell script contains an invoke-expression command and it's not calling another script.
Has anybody experienced a similar problem?

As I remember, there are limitations of scheduled jobs. Try to move your code with Invoke-Command to separated script file and schedule Job as follows:
$trigger = New-JobTrigger -Daily -At '6 am'
$options = New-ScheduledJobOption -WakeToRun -RequireNetwork
Register-ScheduledJob -FilePath .\ScriptWithInvokeCommand.ps1 -Name SampleJobName -Trigger $trigger -ScheduledJobOption $options -RunNow
You can also use Scheduled Task instead of Scheduled Job.

Related

Powershell scheduled script is not running properly

I have a short Powershell script which backup desktop items to D drive
$now = [datetime]::now.ToString('yyyy-MM-dd')
$trigger=new-scheduledtasktrigger -daily -at("08:00am")
$action = new-scheduledtaskaction 'copy "C:\USERS\ADMIN\DESKTOP" "D:\$now" -recurse'
Register-scheduledtask -Action $action -Trigger $trigger -Taskname "dailybackup" -Description "Daily backup"
The code seems valid and scheduled is registered well in scheduler
Get-scheduledtask "dailybackup"
But the task havent executed once but dont know why
anyone knows the solution?
New-ScheduledTaskAction executes commands in the old CMD shell by default. The command you're running doesn't error out because COPY is an ancient CMD built-in. It doesn't actually have the ability to recurse though, so it's not what you want.
To run powershell commands, the task action should execute PowerShell.exe, then have the powershell commands themselves added as arguments like below.
It looks like you want to use the run time date as the folder name $now, so you'll need to re-calculate the date every time it runs,
I also suggest adding -Force to create the target directory as needed,
I'm using here-string formatting #' '# to make quotes and things simpler to handle:
$Action = New-ScheduledTaskAction -Execute 'Powershell.exe' -Argument #'
-Command Copy-Item -Recurse -Force -Path 'C:\USERS\ADMIN\DESKTOP' -Destination "D:\$([datetime]::Now.ToString('yyyy-MM-dd'))"
'#

powershell scheduled job fails to run

I am trying to create a scheduled job using windows powershell, but it can not run correctly.
I check the taskschd.msc and run the job through GUI. And the result is like this "System can not find specified file"(My system is in Chinese language and I translate the result message).
Here is the command I use:
$T = New-JobTrigger -Once -At (Get-Date).AddMinutes(5)
Register-ScheduledJob -Name Test -Trigger $T -ScriptBlock {shutdown.exe /h}
Another question is I have imported module PSScheduledJob, but I cannot track scheduled job information by using command Get-Job.
scheduled tasks and scheduled jobs are different things. if I understand you right you want to create a scheduled task (which can also be managed using taskschd.msc). this can be done as follows:
#create a task action
$taskAction = New-ScheduledTaskAction -Execute 'shutdown.exe' -Argument '/h'
#create a task trigger
$taskTrigger = New-ScheduledTaskTrigger -Once -At (Get-Date).AddMinutes(5)
#register scheduled task with actionn and trigger
Register-ScheduledTask -TaskName 'hibernate computer' -Action $taskAction -Trigger $taskTrigger
after registering the scheduled task you can also see/edit in using taskschd.msc

PowerShell scheduled task: opens PowerShell and script to be run but doesn't execute script

$Trigger = New-ScheduledTaskTrigger -AtLogOn
$User = "Administrator"
$Action = New-ScheduledTask -Execute "PowerShell_ISE.exe" -Argument "C:\Payload\XML_Read.ps1"
Register-ScheduledTask -TaskName "StartupScript_PS" -Trigger $Trigger -User $User -Action $Action -RunLevel Highest -Force
This is my code which creates a scheduled task and runs fine upon logon. the problem is when it logs on it opens PowerShell and the XML_Read file but I have to manually click run for the XML file to be read etc. Is there a way I can modify my code to do this for me? thanks in anticipation.
You can't execute scripts automatically with the ISE. Instead of PowerShell_ISE.exe, use PowerShell.exe.

Register scheduled task with New-ScheduledTaskTrigger to trigger on event ID

Register-ScheduledTask with New-ScheduledTaskTrigger on a Windows event ID
Hello Stack-overflow users. Neither MSDN nor Google yields results...
I configured a couple of scheduled tasks via a Powershell script. The scheduled tasks are set to run at certain times.
This all works fine. But I need to configure another scheduled task which run when a certain event ID is logged in the Windows event logger.
I can set this up manually of course but I want it as part of my automated script.
this is the code I have so far for the scheduled tasks, I need to replace the $Trigger= New-ScheduledTaskTrigger -At 4:00am -Daily section:
Copy-Item "\\networkDrive\Backups\scripts\Reset-Sessions.ps1" "c:\scripts\Reset-Sessions.ps1"
$Trigger= New-ScheduledTaskTrigger -At 4:00am -Daily
$User= 'Nt Authority\System'
$Action= New-ScheduledTaskAction -Execute "Powershell.exe" -Argument "-executionpolicy bypass -File c:\scripts\Reset-Sessions.ps1"
Register-ScheduledTask -TaskName "Reset-Sessions" -Trigger $Trigger -User $User -Action $Action -RunLevel Highest -Force
I have changed some of the directory and file names for online purposes.
I would appreciate it if somebody could steer me into the right direction or assist with an example.
I would prefer to only change the $Trigger portion and not re-write the whole script but I would understand if it is not possible.
I use Powershell version 5.1.
With this answer as a base and some additional help I was able to construct this script
$taskname="Reset-Sessions"
# delete existing task if it exists
Get-ScheduledTask -TaskName $taskname -ErrorAction SilentlyContinue | Unregister-ScheduledTask -Confirm:$false
# get target script based on current script root
$scriptPath=[System.IO.Path]::Combine($PSScriptRoot, "Reset-Sessions.ps1")
# create list of triggers, and add logon trigger
$triggers = #()
$triggers += New-ScheduledTaskTrigger -AtLogOn
# create TaskEventTrigger, use your own value in Subscription
$CIMTriggerClass = Get-CimClass -ClassName MSFT_TaskEventTrigger -Namespace Root/Microsoft/Windows/TaskScheduler:MSFT_TaskEventTrigger
$trigger = New-CimInstance -CimClass $CIMTriggerClass -ClientOnly
$trigger.Subscription =
#"
<QueryList><Query Id="0" Path="Microsoft-Windows-NetworkProfile/Operational"><Select Path="Microsoft-Windows-NetworkProfile/Operational">*[System[(EventID=4004)]]</Select></Query></QueryList>
"#
$trigger.Enabled = $True
$triggers += $trigger
# create task
$User='Nt Authority\System'
$Action=New-ScheduledTaskAction -Execute "Powershell.exe" -Argument "-ExecutionPolicy bypass -File $scriptPath"
Register-ScheduledTask -TaskName $taskname -Trigger $triggers -User $User -Action $Action -RunLevel Highest -Force
The main magic is to use Get-CimClass to get the correct instance, and then populate Subscription from Get-ScheduledTask "Tmp" | Select -ExpandProperty Triggers
Step1:
Go to eventvwr, then create a new scheduled task based on an eventid.
Step2:
Open powershell, then show the scheduled task and see the the way how to was written.
Step3:
Attached and test it in your scrip.
I created a temporary Get-ScheduledTask and run the below line : all what you have to do is to replace the Subscription to meet your requirement.
$A = (Get-ScheduledTask "Tmp" | select -ExpandProperty Triggers)
Here is another method I used in the end to solve the problem:
If you are trying to do this on a Windows Server prior to Server 2012 then you probably don't have the Get-ScheduledTask and New-ScheduledTaskTrigger and the Register-ScheduledTask modules on your Windows system. That means the script in my original question and the accepted answer won't work.
A workaround is to create the desired scheduled task manually and then export it to a xml file. You can edit this file if you like, it is normal plain text xml.
Then have your script and the xml file in the same directory.
Change your script to be compatible with the older version of Powershell to import the xml file.
schtasks /create /tn "Reset-Sessions" /xml "c:\scripts\Reset-Sessions.xml"
Your new scheduled task should now be registered and active.

Schedule a Job in Powershell 3.0

I am working on PS script that will run a task once the computer has been logged in. Here is how I schedule the task:
$trigger = New-JobTrigger -AtLogOn
Register-ScheduledJob -Name TestSchedule -FilePath <filepath> -Trigger $trigger
The script scheduled to run does nothing but launch the command prompt, however nothing is being run once I log in to the computer. I have tried tinkering with it all I could but I get nothing.
Maybe not the best best solution but you could try putting the other script into this "job-script". Like This. Works Fine for me.
$jobname = "xyz"
$JobTrigger = New-JobTrigger -Weekly -At "03:00 AM" -DaysOfWeek Saturday
$MyOptions = New-ScheduledJobOption -ContinueIfGoingOnBattery -HideInTaskScheduler
Register-ScheduledJob -name "$jobname" -scriptblock {$myscript} -trigger $JobTrigger –ScheduledJobOption $MyOptions
I think your code lacks this command:
Set-ScheduledTask -TaskName $name -TaskPath Microsoft\Windows\PowerShell\ScheduledJobs -Principal (New-ScheduledTaskPrincipal -L Interactive -U $env:USERNAME)
$name is the name of your scheduledjob, this command makes the job interactive to the user, if your code still doesn't work, check out this script:
https://gallery.technet.microsoft.com/scriptcenter/PC-Utilities-Downloader-355e5bfe