Task scheduler cannot run script, works with the same user directly over powershell

Bühler Gabriel 71 Reputation points
2024-04-26T10:56:48.9433333+00:00

Hello Everyone

I am trying to run a Scheduled task, that should run a powershell script every evening. Even though I can run the script with the SYSTEM-USER without any issues, it does not work when I try to run over task scheduler.

  • The script does not require any prompts
  • All paths are absolute and task scheduler has the required permissions to use them
  • I do not get any events or error messages, the task just runs until you stop it manually or it gets a timeout
  • The executionpolicy is set to "unrestricted"

Here is the script I am using:

Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
import-module Pnp.Powershell
$url = "myurl"
Connect-PnPOnline -Url $url -ClientId MYID  -Tenant 'URL' -Thumbprint "THUMBPRINTID"
$files = Get-Childitem "CHILDITEMPATH" -Filter *.csv -Force -Recurse
foreach($File in $Files)
{
Add-PnPFile -Path "$($File.Directory)\$($File.Name)"  -Folder "/sites/path/to/folder"
}


Do you have an Idea what this could be?

Thank you for your help.

Kind regards,

Gabriel

Windows Server
Windows Server
A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.
12,176 questions
PowerShell
PowerShell
A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
2,085 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. MotoX80 31,826 Reputation points
    2024-04-26T11:51:56.53+00:00

    Generate a transcript and add diagnostic statements. Check the log file for errors.

    https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.host/start-transcript?view=powershell-5.1

    start-transcript -path C:\Temp\MyScript.log
    Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
    Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
    import-module Pnp.Powershell
    $url = "myurl"
    Connect-PnPOnline -Url $url -ClientId MYID  -Tenant 'URL' -Thumbprint "THUMBPRINTID"
    $files = Get-Childitem "CHILDITEMPATH" -Filter *.csv -Force -Recurse
    "We found {0} files." -f $files.count
    foreach($File in $Files)
    {
       "File: {0}" -f $file.name
       Add-PnPFile -Path "$($File.Directory)\$($File.Name)"  -Folder "/sites/path/to/folder"
    }
    stop-transcript
    
    0 comments No comments