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 for business | Windows Server | User experience | PowerShell
Windows for business | Windows Server | User experience | Other
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Rich Matheisen 48,036 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


Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.