Public/Remove-SharingLink.ps1
|
function Remove-SharingLink { <# .SYNOPSIS Revoke sharing links produced by Get-SharingLink. .DESCRIPTION Takes the objects Get-SharingLink emits and removes those links. Because it reads from the pipeline, you revoke exactly what you filtered - the anonymous ones, the expired ones, everything on one site - by narrowing the Get-SharingLink results first. Supports -WhatIf. Run it with -WhatIf before you run it for real. .EXAMPLE Get-SharingLink -SiteUrl $url -UseExistingConnection | Where-Object Scope -eq 'Anonymous' | Remove-SharingLink -WhatIf .EXAMPLE Get-SharingLink -Tenant -TenantAdminUrl $admin -ClientId $id -Interactive -MinimumRisk Critical | Remove-SharingLink #> [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')] param( [Parameter(Mandatory, ValueFromPipeline)] [psobject] $Link ) begin { # Accumulate a run total so a bulk revoke ends with a clear summary # rather than the user counting warnings. $script:revokedCount = 0 $script:failedCount = 0 } process { # Only act on objects that carry what a revoke needs. Under StrictMode a # bare $Link.ItemPath THROWS when the property is absent, so test for the # property's existence first rather than its value. $hasPath = $Link.PSObject.Properties.Match('ItemPath').Count -gt 0 -and $Link.ItemPath $hasId = $Link.PSObject.Properties.Match('LinkId').Count -gt 0 -and $Link.LinkId if (-not $hasPath -or -not $hasId) { Write-Warning "Skipping an object with no ItemPath/LinkId - was it produced by Get-SharingLink?" return } $target = "$($Link.Scope)/$($Link.Access) link on $($Link.ItemName)" if ($PSCmdlet.ShouldProcess($target, 'Revoke sharing link')) { try { Invoke-WithRetry -Because "revoke on $($Link.ItemName)" -Action { if ($Link.ItemType -eq 'Folder') { Remove-PnPFolderSharingLink -Folder $Link.ItemPath -Identity $Link.LinkId -Force -ErrorAction Stop } else { Remove-PnPFileSharingLink -FileUrl $Link.ItemPath -Identity $Link.LinkId -Force -ErrorAction Stop } } $script:revokedCount++ Write-Verbose "Revoked $target" } catch { $script:failedCount++ Write-Warning "Failed to revoke $target : $($_.Exception.Message)" } } } end { if ($script:revokedCount -or $script:failedCount) { $msg = "Revoked $script:revokedCount link(s)" if ($script:failedCount) { $msg += ", $script:failedCount failed" } Write-Information $msg -InformationAction Continue } } } |