UcLobbySharePoint.psm1
|
function Get-UcUPNFromString { param ( [string]$InputStr ) $regexUPN = "([^|]+@[a-zA-Z0-9_\-\.]+\.[a-zA-Z]*)" try { $RegexTemp = [regex]::Match($InputStr, $regexUPN).captures.groups if ($RegexTemp.Count -ge 2) { $outUPN = $RegexTemp[1].value } return $outUPN } catch { return "" } } function Export-UcOneDriveWithMultiplePermissions { <# .SYNOPSIS Generate a report with OneDrive's that have more than a user with access permissions. .DESCRIPTION This script will check all OneDrives and return the OneDrive that have additional users with permissions. Author: David Paulino Requirements: EntraAuth PowerShell Module (Install-Module EntraAuth) or Microsoft Graph Authentication PowerShell Module (Install-Module Microsoft.Graph.Authentication) Microsoft Graph Scopes: "Sites.Read.All" Note: Currently the SharePoint Sites requires to authenticate to Graph API with AppOnly https://learn.microsoft.com/graph/auth/auth-concepts .PARAMETER OutputPath Allows to specify the path where we want to save the results. By default, it will save on current user Download. .PARAMETER MultiGeo Required if Tenant is MultiGeo .EXAMPLE PS> Export-UcOneDriveWithMultiplePermissions .EXAMPLE PS> Export-UcOneDriveWithMultiplePermissions -MultiGeo #> param( [string]$OutputPath, [switch]$MultiGeo ) #region Graph Connection, Scope validation and module version if (!(Test-UcServiceConnection -Type MSGraph -Scopes "Sites.Read.All" -AltScopes ("Sites.ReadWrite.All") -AuthType "Application")) { return } Test-UcPowerShellModule | Out-Null #endregion $startTime = Get-Date #Graph API request is different when the tenant has multigeo if ($MultiGeo) { $outFile = "OneDrivePermissions_MultiGeo_" + (Get-Date).ToString('yyyyMMdd-HHmmss') + ".csv" $GraphPathSites = "/sites/getAllSites?`$select=id,displayName,isPersonalSite,WebUrl&`$top=999" } else { $outFile = "OneDrivePermissions_" + (Get-Date).ToString('yyyyMMdd-HHmmss') + ".csv" $GraphPathSites = "/sites?`$select=id,displayName,isPersonalSite,WebUrl&`$top=999" } #Verify if the Output Path exists if ($OutputPath) { if (!(Test-Path $OutputPath -PathType Container)) { Write-Host ("Error: Invalid folder " + $OutputPath) -ForegroundColor Red return } $OutputFilePath = [System.IO.Path]::Combine($OutputPath, $outFile) } else { $OutputFilePath = [System.IO.Path]::Combine($env:USERPROFILE, "Downloads", $outFile) } $OneDriveProcessed = 0 $OneDriveFound = 0 $BatchNumber = 1 $row = "OneDriveDisplayName,OneDriveUrl,Role,UserWithAccessDisplayName,UserWithAccessUPN,UserWithAccessSharePointLogin,OneDriveID,PermissionID" + [Environment]::NewLine do { try { $ResponseSites = Invoke-UcGraphRequest -Path $GraphPathSites $GraphRequestSites = $ResponseSites.'@odata.nextLink' #Currently the SharePoint API doenst support filter for isPersonalSite, so we need to filter it $tempOneDrives = $ResponseSites.value | Where-Object { $_.isPersonalSite -eq $true } #Adding a progress messsage to show status foreach ($OneDrive in $tempOneDrives) { if ($OneDriveProcessed % 10 -eq 0) { Write-Progress -Activity "Looking for addtional users in OneDrive permissions" -Status "Batch #$BatchNumber - Number of OneDrives Processed $OneDriveProcessed" } $GPOneDrivePermission = "/sites/" + $OneDrive.id + "/drive/root/permissions" try { $OneDrivePermissions = Invoke-UcGraphRequest -Path $GPOneDrivePermission if ($OneDrivePermissions.count -gt 1) { foreach ($OneDrivePermission in $OneDrivePermissions) { if ($OneDrivePermission.grantedToV2.siteuser.displayName -ne $OneDrive.displayName) { $tempUPN = Get-UcUPNFromString $OneDrivePermission.grantedToV2.siteuser.loginName $row += $OneDrive.displayName + "," + $OneDrive.WebUrl + "," + $OneDrivePermission.roles + ",`"" + $OneDrivePermission.grantedToV2.siteuser.displayName + "`"," + $tempUPN + "," + $OneDrivePermission.grantedToV2.siteuser.loginName + ",`"" + $OneDrive.id + "`"," + $OneDrivePermission.id Out-File -FilePath $OutputFilePath -InputObject $row -Encoding UTF8 -append $row = "" $OneDriveFound++ } } } $OneDriveProcessed++ } catch { } } $BatchNumber++ } catch { break } } while (![string]::IsNullOrEmpty($GraphRequestSites)) $endTime = Get-Date $totalSeconds = [math]::round(($endTime - $startTime).TotalSeconds, 2) $totalTime = New-TimeSpan -Seconds $totalSeconds Write-Host "Total of OneDrives processed: $OneDriveProcessed, total OneDrives with additional users with permissions: $OneDriveFound" -ForegroundColor Cyan if ($OneDriveFound -gt 0) { Write-Host ("Results available in " + $OutputFilePath) -ForegroundColor Cyan } Write-Host "Execution time:" $totalTime.Hours "Hours" $totalTime.Minutes "Minutes" $totalTime.Seconds "Seconds" -ForegroundColor Green } function Export-UcSharePointSitesWithEmptyFiles { <# .SYNOPSIS Generate a report with OneDrive's that have more than a user with access permissions. .DESCRIPTION This cmdlet will check all SharePoint Sites and OneDrives looking for empty files (size = 0). Please note that by default Query parameter will PDF. Author: David Paulino Requirements: EntraAuth PowerShell Module (Install-Module EntraAuth) or Microsoft Graph Authentication PowerShell Module (Install-Module Microsoft.Graph.Authentication) Microsoft Graph Scopes: "Sites.Read.All" Note: Currently the SharePoint Sites requires to authenticate to Graph API with AppOnly https://learn.microsoft.com/graph/auth/auth-concepts .PARAMETER Query "The query text used to search for items. Values may be matched across several fields including filename, metadata, and file content. https://learn.microsoft.com/graph/api/driveitem-search?view=graph-rest-1.0&tabs=http#function-parameters .PARAMETER OutputPath Allows to specify the path where we want to save the results. By default, it will save on current user Download. .PARAMETER MultiGeo Required if Tenant is MultiGeo .PARAMETER IncludeOneDrive If OneDrives should also be included in the report. .EXAMPLE PS> Export-UcSharePointSitesWithEmptyFiles .EXAMPLE PS> Export-UcSharePointSitesWithEmptyFiles -MultiGeo .EXAMPLE PS> Export-UcSharePointSitesWithEmptyFiles -IncludeOneDrive #> param( [string]$Query = "PDF", [string]$OutputPath, [switch]$MultiGeo, [switch]$IncludeOneDrive ) #region Graph Connection, Scope validation and module version if (!(Test-UcServiceConnection -Type MSGraph -Scopes "Sites.Read.All" -AltScopes ("Sites.ReadWrite.All") -AuthType "Application")) { return } Test-UcPowerShellModule | Out-Null #endregion $startTime = Get-Date #Graph API request is different when the tenant has multigeo if ($MultiGeo) { $outFile = "SharePointEmptyFiles_MultiGeo_" + (Get-Date).ToString('yyyyMMdd-HHmmss') + ".csv" $GraphRequestSites = "/sites/getAllSites?`$select=id,displayName,isPersonalSite,WebUrl&`$top=999" } else { $outFile = "SharePointEmptyFiles_" + (Get-Date).ToString('yyyyMMdd-HHmmss') + ".csv" $GraphRequestSites = "/sites?`$select=id,displayName,isPersonalSite,WebUrl&`$top=999" } #Verify if the Output Path exists if ($OutputPath) { if (!(Test-Path $OutputPath -PathType Container)) { Write-Host ("Error: Invalid folder " + $OutputPath) -ForegroundColor Red return } $OutputFilePath = [System.IO.Path]::Combine($OutputPath, $outFile) } else { $OutputFilePath = [System.IO.Path]::Combine($env:USERPROFILE, "Downloads", $outFile) } $SharePointSitesProcessed = 0 $EmptyFilesFound = 0 $BatchNumber = 1 $row = "SiteDisplayName,SiteUrl,FileName,Size,createDate,createdByDisplayName,createdByemail,lastModifiedDate,lastModifiedByDisplayName,lastModifiedByEmail" + [Environment]::NewLine do { try { $ResponseSites = Invoke-UcGraphRequest -Path $GraphRequestSites $GraphRequestSites = $ResponseSites.'@odata.nextLink' if ($IncludeOneDrive) { $tempSites = $ResponseSites.value } else { $tempSites = $ResponseSites.value | Where-Object { $_.isPersonalSite -eq $false } } #Adding a progress messsage to show status foreach ($Site in $tempSites) { if ($SharePointSitesProcessed % 10 -eq 0) { Write-Progress -Activity "For empty files" -Status "Batch #$BatchNumber - Number of Sites Processed $SharePointSitesProcessed" } $GRSharePointDrive = "/sites/" + $Site.id + "/drive/root/search(q='$Query')" try { $SPFiles = (Invoke-UcGraphRequest -Path $GRSharePointDrive) if ($SPFiles.value.count -ge 1) { foreach ($SPFile in $SPFiles.value) { if ($SPFile.size -eq 0) { $row += $Site.displayName + "," + $Site.WebUrl + "," + $SPFile.name + "," + $SPFile.size + "," + $SPFile.createdDateTime + "," + $SPFile.createdBy.user.displayName + "," + $SPFile.createdBy.user.email + "," + $SPFile.lastModifiedDateTime + "," + $SPFile.lastModifiedBy.user.displayName + "," + $SPFile.lastModifiedBy.user.email Out-File -FilePath $OutputFilePath -InputObject $row -Encoding UTF8 -append $row = "" $EmptyFilesFound++ } } } $SharePointSitesProcessed++ } catch { } } $BatchNumber++ } catch { break } } while (![string]::IsNullOrEmpty($GraphRequestSites)) $endTime = Get-Date $totalSeconds = [math]::round(($endTime - $startTime).TotalSeconds, 2) $totalTime = New-TimeSpan -Seconds $totalSeconds Write-Host "Total of Sites processed: $SharePointSitesProcessed, total empty files: $EmptyFilesFound" -ForegroundColor Cyan if ($EmptyFilesFound -gt 0) { Write-Host ("Results available in " + $OutputFilePath) -ForegroundColor Cyan } Write-Host "Execution time:" $totalTime.Hours "Hours" $totalTime.Minutes "Minutes" $totalTime.Seconds "Seconds" -ForegroundColor Green } function Export-UcSharePointSitesWithHold { <# .SYNOPSIS Report with SharePoint Sites/OneDrive with a hold in place. .DESCRIPTION This cmdlet will generate a csv file with SharePoint Sites and OneDrive with a hold in place. Author: David Paulino Requirements: SharePoint Online PowerShell Install-Module -Name Microsoft.Online.SharePoint.PowerShell Connect-SPOService -Url https://contoso-admin.sharepoint.com Security & Compliance PowerShell Install-Module -Name ExchangeOnlineManagement Connect-IPPSSession -UserPrincipalName user.adm@contoso.onmicrosoft.com .PARAMETER OutputPath Allows to specify the path where we want to save the results. By default, it will save on current user Download. .PARAMETER IncludeOneDrive If OneDrives should also be included in the report. .EXAMPLE PS> Export-UcSharePointSitesWithHold .EXAMPLE PS> Export-UcSharePointSitesWithHold -IncludeOneDrive #> param( [string]$OutputPath, [switch]$IncludeOneDrive ) $startTime = Get-Date #TODO: SharePoint and Security and Compliance Connectivity check. #2025-07-23: All logic to check if we run this and getting the module name moved to the Test-UcPowerShellModule. Test-UcPowerShellModule | Out-Null #endregion $outFile = "SharePointSitesWithHolds_" + (Get-Date).ToString('yyyyMMdd-HHmmss') + ".csv" #Verify if the Output Path exists if ($OutputPath) { if (!(Test-Path $OutputPath -PathType Container)) { Write-Host ("Error: Invalid folder " + $OutputPath) -ForegroundColor Red return } $OutputFilePath = [System.IO.Path]::Combine($OutputPath, $outFile) } else { $OutputFilePath = [System.IO.Path]::Combine($env:USERPROFILE, "Downloads", $outFile) } if ($IncludeOneDrive) { Write-Warning "SharePoint Sites and OneDrives" $activityMsg = "Checking SharePoint Sites and OneDrives with Holds" $SPSites = Get-SPOSite -Limit all -IncludePersonalSite:$true } else { Write-Warning "Getting the SharePoint Sites" $activityMsg = "Checking SharePoint Sites with Holds" $SPSites = Get-SPOSite -Limit all } $SitesProcessed = 1 $SitesTotal = $SPSites.count $row = "SiteURL,HoldID,HoldCreatedDate,HoldCreatedBy,HoldEnabled,Type,IsAdaptivePolicy" + [Environment]::NewLine foreach ($SPSite in $SPSites) { try { $SiteHolds = Invoke-HoldRemovalAction -Action GetHolds -SharePointLocation $SPSite.Url -ErrorAction SilentlyContinue Write-Progress -Activity $activityMsg -Status ("Processing site " + $SPSite.Url + " - " + $SitesProcessed + " of " + $SitesTotal) foreach ($SiteHold in $SiteHolds) { $SiteCompliancePolicy = Get-RetentionCompliancePolicy -Identity $SiteHold $row += $SPSite.Url + "," + $SiteHold + "," + $SiteCompliancePolicy.WhenCreatedUTC + "," + $SiteCompliancePolicy.CreatedBy + "," + $SiteCompliancePolicy.Enabled + "," + $SiteCompliancePolicy.Type + "," + $SiteCompliancePolicy.IsAdaptivePolicy Out-File -FilePath $OutputFilePath -InputObject $row -Encoding UTF8 -append $row = "" } $SitesProcessed++ } catch { write-warning ("Failed to get Holds for site: " + $SPSite.Url) } } $endTime = Get-Date $totalSeconds = [math]::round(($endTime - $startTime).TotalSeconds, 2) $totalTime = New-TimeSpan -Seconds $totalSeconds Write-Host ("Results available in " + $OutputFilePath) -ForegroundColor Cyan Write-Host "Execution time:" $totalTime.Hours "Hours" $totalTime.Minutes "Minutes" $totalTime.Seconds "Seconds" -ForegroundColor Green } |