Microsoft Graph scheduled task script while signed out doesn't work

Sat 0 Reputation points
2023-09-20T15:47:43.63+00:00

Whenever I run the script manually in the task scheduler it works fine and able to output the logfile but when I run it as a scheduled task with setting "Whether user is logged on or not" it doesn't add a log file. it seems like it's not even connecting to graph.

connect-mggraph -TenantId "Tenant_ID" -ClientId "Client_ID" -CertificateThumbprint "Cert_Thumb"

Start-sleep 5

$logfile = "File Path"

Get-MgUserLicenseDetail -UserID "sampleUser" | out-file $logfile -Append

Windows Server
Windows Server
A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.
11,165 questions
Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,183 questions
PowerShell
PowerShell
A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
1,571 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Rich Matheisen 43,241 Reputation points
    2023-09-20T18:03:46.3066667+00:00

    Is the scheduled task using your credential or the default SYSTEM user?

    The SYSTEM account, when authenticating, uses the name of your machine (e.g., COMPUTER$) but doesn't provide a password.

    You should be including error handling in your scripts (and sometimes transcriptions) and recording any errors the script encounters. Without knowing why something doesn't (or didn't) works without knowing why it failed will lead to very lengthy debugging sessions.


  2. Sat 0 Reputation points
    2023-09-21T09:05:14.0666667+00:00
    # Load from local machine store.
    $cert = Get-ChildItem Cert:\LocalMachine\My\$CertThumbprint
    Connect-Graph -Certificate $cert -TenantId $TenantId -ClientId $ClientId
    
    # Load from path.
    $password= "SomePassword"
    $passwordSecure = ConvertTo-SecureString -AsPlainText -Force $password
    
    $cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2("C:\Certificates\mycert.pfx", $passwordSecure)
    Connect-Graph -Certificate $cert -TenantId $TenantId -ClientId $ClientId
    
    

    I got this script from this thread and it resolved my issue where Certificate can't be read. Thanks very much for the advise of add an error message, might take longer to debug the issue without your advise.
    https://github.com/microsoftgraph/msgraph-sdk-powershell/issues/675