The current connection holds no SharePoint context. Please use one of the Connect-PnPOnline commands which uses the -Url argument to connect.

Hi Team

I have this Powershell script that i am running via AR as a scheduled task. The script updates the permissions on One Drive. 

Now if i run the script inside AR or outside ARS as a manual run then everything works as it should. However almost every time when its run as the scheduled task i see this error. 

The current connection holds no SharePoint context. Please use one of the Connect-PnPOnline commands which uses the -Url argument to connect.

Any ideas? i have changed times of days its run , made sure nothing else is running but same issue. 

#Set Runtime Parameters
#Obtain Azure Location from Scheduled Task parameter
$AzureLocation = $Task.DirObj.Parameters.Value("AzureLocation").Value

#Date
$DateYear = $((Get-Date).ToString('yyyy'))
$DateMonth = $((Get-Date).ToString('MMM'))
$DateDay = $((Get-Date).ToString('dd'))
$Time = Get-Date -Format "HH-mm"

#Create Log Folder structure based on Date
New-Item -ItemType Directory -Path "\\PATH-HERE\$DateYear\$DateMonth\$DateDay\Logs" -Force

$logfile = "\\PATH-HERE\$DateYear\$DateMonth\$DateDay\Logs\$AzureLocation-$Time.txt"

#The GroupID will be different for each group
#onPrem Group
$ADGroupID01="GUID-Here"
$LoginName01 = "Login-Name-Here"
#Azure Group
$ADGroupID02="GUID-Here"
$LoginName02 = "Logon-Name-Here"
#===================================================================
#Azure Location
switch ($AzureLocation) {
    'GBR' { $SPURL = 'https://domain-name-here-admin.sharepoint.com' }
    default   { $SPURL = "https://domain-name-here$AzureLocation-admin.sharepoint.com"}
}

#Share Point Connection Properties
    $CxParams = @{
    URL = $SPURL
    ClientID = "ID-Here"
    Tenant = "domain-name-here.onmicrosoft.com"
    Thumbprint = "Cert-Thumprint"
}

#Connect to SharePoint Online
Connect-PnPOnline @CxParams

#Get all OneDrive for Business Site collections
$OneDriveSites = Get-PnPTenantSite -IncludeOneDriveSites -Filter "Url -like '-my.sharepoint.com/personal/'"
#Write-Host "Total Number of OneDrive Sites Found: "$OneDriveSites.count
Write-Output "Total Number of OneDrive Sites Found: "$OneDriveSites.count | Out-File $logfile -Append
#Add Site Collection Admin to each OneDrive
foreach($Site in $OneDriveSites)
{
    #Write-Host "Adding Site Collection Admin to: "$Site.URL
    Write-Output "Adding Site Collection Admin to: "$Site.URL | Out-File $logfile -Append
    
    #Enable
	Set-PnPTenantSite -Identity $site.url -Owners @($LoginName01, $LoginName02) -ErrorAction SilentlyContinue

}
#Write-Host "Site Collection Admin Added to All OneDrive Sites Successfully!"
Write-Output "Site Collection Admin Added to All OneDrive Sites Successfully!" | Out-File $logfile -Append

Disconnect-PnPOnline

exit
 
 

Parents Reply Children