Ok!
Ok! I repeated the whole procedure and now it works.
If it can be useful, I recap all the steps made:
- I opened a Windows PowerShell 5.1 instance with
psexec.exeacting asnt authority\system. - From that shell, I ran
Install-Module PSWindowsUpdate(which required theNuGet provider, automatically installed after giving permission interactively), giving permission to install from the repositoryPSGallery. - I verified from that shell that
Get-WindowsUpdateactually is recognized and acts as expected. - (Is this relevant?) From that shell I also ran
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser, so this has been applied to usernt authority\system. - From the GUI, I opened another Windows PowerShell 5.1 instance (note that this is WIndows PowerShell 5.1, not PowerShell 7.4), running as Administrator. So, this shell is ran by my local user account, acting as Administrator.
- I configured a Scheduled Task as suggested above:
$action = New-ScheduledTaskAction -Execute 'PowerShell' -Argument '-F C:\myscript.ps1'
$trigger = New-ScheduledTaskTrigger -Daily -At 11:00
$principal = New-ScheduledTaskPrincipal -UserID "NT AUTHORITY\SYSTEM" -LogonType ServiceAccount -RunLevel Highest
$task = New-ScheduledTask -Action $action -Trigger $trigger -Principal $principal
$task.Settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries
Register-ScheduledTask check_updates -InputObject $task
- Note that, by specifying
-Execute 'PowerShell', this task is run using Windows PowerShell 5.1 and not PowerShell 7.4. - The task successfully ran and the log file was written as expected.
This is ok now.
Probably the error of the previous post was due to the fact that for the steps 5-6 I was using a PowerShell 7.4 instance, instead of a Windows PowerShell 5.1 instance. However, scheduled tasks are visible on both PowerShell 7.4 and Windows PowerShell 5.1, regardless of where they have been created.
I repeated all the above steps using PowerShell 7.4 instead of Windows PowerShell 5.1. I had to perform step 4 before step 2.
This time, the script ran and it provided a LastTaskResult : 0. However, only unreadable characters were printed in the log file (and they are different each time), instead of the expected strings provided in the script.
This is the Actions tab in the properties of the Scheduled Task from the GUI Task Scheduler:
Actions
Start a program
C:\Program Files\PowerShell\7\pwsh.exe -F C:\myscript.ps1
With more detail, if I press the “Edit” button in the “Actions” tab:
Action: Start a program
Settings
Program/script: C:\Program Files\PowerShell\7\pwsh.exe
Add arguments (optional): -F C:\myscript.ps1
Start in (optional):
It would be good if this scheduled task could be configured and run also in PowerShell 7.4, but if it’s not possible, Windows PowerShell 5.1 is enough.
Thanks for your help and suggestions!