最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

PnP.PowerShell not working when running as scheduled-task - Stack Overflow

programmeradmin5浏览0评论

I want to automate some SharePoint-related tasks via PnP.PowerShell. The script itself is done and works fine if I run it manually. But If I run it via task scheduler it only works with the setting "Run only when user is logged on". Putting it to "Run wheter user is logged on or not" makes it stop working at the point where it tries to connect to the SharePoint (the script writes a log file for me to see). I check if the website itself is available to see if the internet connection might have been cut but it's all well.

My simplified code below:

function Write-Log($Message)
{
    "$([System.DateTime]::Now.ToString("dd.MM.yyyy - HH:mm:ss")) | $Message" | Out-File -FilePath "$PSScriptRoot\log1.txt" -Append
}

function Cut-Log($LineCount)
{
    $LogContent = [System.String[]] (Get-Content "$PSScriptRoot\log1.txt")

    if ($LogContent.Count -gt $LineCount)
    {
        $NewLogContent = [System.String[]]::new($LineCount)
    
        $LogContent[($LogContent.Count - $LineCount)..($LogContent.Count - 1)].CopyTo($NewLogContent,0)
        $NewLogContent | Out-File "$PSScriptRoot\log1.txt"
    }
}

function Start-SharePointSync($PnPConnection)
{
    <# code #>
}


Write-Log -Message "-----"
Write-Log -Message "Start"
Write-Log -Message "Process-ID: $PID"
Write-Log -Message "PS-Version: $($PSVersionTable.PSVersion.ToString())"

try
{
    Import-Module PnP.PowerShell
    Write-Log "PnP.Powershell - import successful"
}
catch
{
    Write-Log "PnP.Powershell - import error"
    Write-Log "Script aborted."
    exit
}

$SPURL = ";

try
{
    $ConnectionTest = (Invoke-WebRequest $SPURL).StatusDescription
}
catch
{
    $ConnectionTest = "NOT OK"
}
Write-Log "Web-connection to SharePoint: $ConnectionTest"

if ($ConnectionTest -EQ "OK")
{
    try
    {
        Write-Log "Starting PnP-connection to '$SPURL'"
        $PNPCon = Connect-PnPOnline -Url $SPURL -UseWebLogin -ReturnConnection
        Write-Log "PnP connection successful"
    }
    catch
    {
        Write-Log "PnP connection failed"
    }

    Start-SharePointSync -PnPConnection $PNPCon

    write-log "Script Finished."

}
else
{
    Write-Log "Script aborted."
}

Cut-Log 1000

My log-output:

20.03.2025 - 14:17:18 | -----
20.03.2025 - 14:17:18 | Start
20.03.2025 - 14:17:18 | Process-ID: 25328
20.03.2025 - 14:17:18 | PS-Version: 7.4.7
20.03.2025 - 14:17:19 | PnP.Powershell - import successful
20.03.2025 - 14:17:19 | Web-connection to SharePoint: OK
20.03.2025 - 14:17:19 | Starting PnP-connection to ''

My script apparently just freezes at that point.

发布评论

评论列表(0)

  1. 暂无评论