Currently I have this script:
#Config Parameters
$AdminSiteURL="adminsite"
$UserAccount = "henk#test.nl"
#Connect to SharePoint Online Tenant Admin
Connect-SPOService -URL $AdminSiteURL -Credential (Get-Credential)
#Get all Site Collections
$SitesCollections = Get-SPOSite -Template STS#0 -Limit ALL
#Iterate through each site collection
ForEach($Site in $SitesCollections)
{
Write-host -f Yellow "Checking Site Collection:"$Site.URL
#Get the user from site collection
$User = Get-SPOUser -Limit All –Site $Site.URL | Where {$_.LoginName -eq $UserAccount}
#Remove the User from site collection
If($User)
{
#Remove the user from the site collection
#Remove-SPOUser -Site $Site.URL –LoginName $UserAccount
Write-host -f Green "`tUser $($UserAccount) has been removed from Site collection!"
}
}
Our domain is #companyname.nl so for example when I search for the user test#companyname.nl it finds the users in the site collection and it deletes the user.
But when I use an external email address for example test#gmail.com which is also in the sharepoint site collection as guest it cannot find it.
Why is that?
Per my test, to get external user, you should add #ext##companyname.nl at the end of the external email address.
For example:
Get-SPOUser -Site "https://yoursite" -LoginName "test_gmail.com#ext##contoso.onmicrosoft.com"
Related
I have this script :-
#Parameters
$SiteURL="https://***.sharepoint.com/"
$FolderSiteRelativeURL = "/Shared Documents"
$PermissionToAdd="Contribute"
$PermissionToRead="Read"
#Connect to the Site collection
Connect-PnPOnline -URL $SiteURL -UseWebLogin
#Get the Folder from site relative URL
#$FolderOld = Get-PnPFolder -Url $FolderSiteRelativeURL -Includes ListItemAllFields.HasUniqueRoleAssignments, ListItemAllFields.ParentList, ListItemAllFields.ID
$Folders=Get-PnPFolderItem -FolderSiteRelativeUrl $FolderSiteRelativeURL -ItemType Folder | Where {$_.Name -ne "Forms"}
ForEach($SubFolder in $Folders)
{
$n= $FolderSiteRelativeURL+"/"+$SubFolder.Name
Write-host $n
$sub=Get-PnPFolder -Url $n -Includes ListItemAllFields.HasUniqueRoleAssignments, ListItemAllFields.ParentList, ListItemAllFields.ID, ListItemAllFields.RoleAssignments
If($sub.ListItemAllFields.HasUniqueRoleAssignments)
{
Write-host "Folder is already with broken permissions!" -f Yellow
}
Else
{
Write-host "Else is running" -f Yellow
#Break Folder permissions - keep all existing permissions & keep Item level permissions
$sub.ListItemAllFields.BreakRoleInheritance($False,$False)
Invoke-PnPQuery
ForEach($RoleAssignment in $sub.ListItemAllFields.RoleAssignments)
{
///code goes here
}
Write-host "Folder's Permission Inheritance is broken!!" -f Green
}
}
Which gets all the document library's root folders >> then define unique permissions on them and do not copy the permissions.
now i need to grant the following permissions to the folders which got unique permissions:-
SharePoint group named "Management" with id =9 >> Contribute.
Mail enabled security group named "info#ourcompnay.com" >> Read
Office 365 group named "managment#ourcompany.com" >> Contribute
so can anyone advice on how i need to modify my code inside the ///code goes here to assign 3 permissions to each folder?
Thanks
(FIRST POST - I will do my best to summerize, forgive me ahead of time)
I have a SharePoint site with a list of sites to be deleted, problem is, some of the sites to be deleted have subsites that need to be deleted before the deletion can occure. I have a basic Powershell script that will delete the site as long as there are no subsites.
I am trying to come up with either a method to delete the subsites if the listed site to be deleted has subs or a way to catch the ones that have an error to enter data into a column on the same list or output a file AND to continue deleting the sites without subs.
Here is what I have so far:
#========================================================================#
# Delete confirmed sites #
#========================================================================#
function deleteSites_old ($url, $listName) {
$web = get-SPWeb $url
$list = $web.Lists[$listname]
$items = $list.items | Where-Object {($_['Status'] -eq 'Delete')}
Write-host "List $($list.title) has $($items.count) entries to be deleted"
foreach ($item in $items) {
$siteURL = $item["URL"]
$siteOwner = $itme["SiteOwner"]
write-host $siteURL $siteOwner
try {
write-host "Site deletion"
#Remove-SPWeb -Identity $siteURL -Recycle
}
catch [Microsoft.SharePoint.Powershell.SPCmdRemoveWeb] {
"There was a problem deleting web site $($siteURL)"
}
#Remove-SPWeb -Identity $siteURL -Recycle
#$ListItem["Status"] = "DELETED"
#$ListItem.update()
}
#DELETES THE INSTANCE
$web.Dispose()
}
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
$Site = '[URL]'
$list = "[List Name]"
deleteSites_old $Site $List
I am still testing so I have commented out as I continue. Thanks ahead of time, I did search the forum first but only found questions related to SPOnline or SP13 (with $ChildSites but couldn't get it to work for my environment)
if i provide a site name and a list name , the script should delete the items in the list and then delete the list? is this possible in powershell or javascript? can anyone help me?
This is for SharePoint online so how to make below code to work for SharePoint online?
## SP URL
Write-Host "Provide SharePoint URL:" -ForegroundColor Yellow
$webURL = Read-Host
$web = Get-SPweb $webURL
## LIST NAME
Write-Host "Enter name of the list:" -ForegroundColor Yellow
$listName = Read-Host
$list = $web.lists[$listName]
## SET QUERY
$query = New-Object Microsoft.SharePoint.SPQuery
$query.ViewAttributes = "Scope='Recursive'"
$query.RowLimit = 1000
$query.ViewFields = "<FieldRef Name='ID'/>"
$query.ViewFieldsOnly = $true
## EXECUTE
do
{
$listItems = $list.GetItems($query)
$query.ListItemCollectionPosition = $listItems.ListItemCollectionPosition
foreach ($item in $listItems)
{
Write-Host "Deleting Item - $($item.Id)" -ForegroundColor Yellow
$list.GetItemById($item.Id).delete()
}
#Reset the "Allow Deletion" Flag
$list.AllowDeletion = $true
$list.Update()
$list.Delete()
}
while ($null -eq $query.ListItemCollectionPosition)
Write-Host "Script finished." -ForegroundColor Green ``````````````
Deleting items from specified list or/and the list itself is possible both using PowerShell and javascript.
For the javascript you may either use REST API calls for that or JSOM. Here you may find examples how to use JSOM to perform basic CRUD operations -> How to: Create, Update, and Delete List Items Using JavaScript. Please be aware that in order for JSOM to work it needs a SP context which may be created only when the JS is executed in the context of SharePoint (so for example on a SharePoint page)
as for PowerShell you may use PnP PowerShell cmdlets for it. Here is the MSDN article how to get the PnP PowerShell for SharePoint Online and connect to a site and here are the commands you were asking for: the Remove-PnPListItem and Remove-PnPList
You could try to use pnp powershell:
Delete item:
Get-PnPList -Identity Lists/MyList | Get-PnPListItem -PageSize 100 -ScriptBlock { Param($items)
$items.Context.ExecuteQuery() } | % {$_.DeleteObject()}
Delete list:
Remove-PnPList -Identity "test5" -Force
Delete the entire list directly, the item will also be deleted.
Download pnp powershell here.
Is it possible to use the Connect-SPOService cmdlet with an application identifier & secret? I need to get information about site collections within an azure function that are only available through the get-sposite cmdlet.
I'm trying to set up an Azure Function that uses the SharePoint Online PowerShell module to report all site collections that have external sharing enabled.
As I don't want to include my personal credentials in this Azure Function I set up an application identifier in Azure AD.
I am able to use this app id with the PnP Cmdlets (connect-pnponline -appid ...) but the pnp command get-pnpsite do not return the needed detail information.
Below is the code with pnp framework, where all Sharing* properties are empty.
Connect-PnPOnline -AppId $appid -AppSecret $appsecret -Url $adminUrl
$content = #()
Get-PnPTenantSite -Filter "Url -notlike ""*/personal*""" | ? {$_.SharingCapability -ne "Disabled" } | % {
$connection = Connect-PnPOnline -ReturnConnection -Url $_.url -AppId $AppId -AppSecret $AppSecret
$site = Get-PnPSite -Connection $connection;
$content += #{
title= $site.Title;
url=$site.Url;
owner=$site.Owner;
SharingCapability=$site.SharingCapability;
SharingDomainRestrictionMode=$site.SharingDomainRestrictionMode;
SharingAllowedDomainList=$site.SharingAllowedDomainList;
SharingBlockedDomainList=$site.SharingBlockedDomainList}
}
This Code works, but needs actural user credentials:
param (
# Parameter help description
[Parameter(Mandatory=$true)]
[string]$TenantName,
# Parameter help description
[Parameter(Mandatory=$true)]
[string]$DestinationPath
)
$dateStr = Get-Date -Format yyyy-MM-dd_HH-mm-ss
$filename = "ExternalSharingReport_$dateStr.csv"
$content = #()
$adminUrl = "https://$TenantName-admin.sharepoint.com"
Connect-SPOService -Url $adminUrl
$content += "Title; Url; Owner; SharingCapability; SharingDomainRestrictionMode; SharingAllowedDomainList; SharingBlockedDomainList"
Get-SpoSite | ? {$_.Url -notlike "*/personal*" -AND $_.SharingCapability -ne "Disabled" } | % {
$site = Get-SPOSite $_.url;
$content += "$($site.Title); $($site.Url); $($site.Owner); $($site.SharingCapability); $($site.SharingDomainRestrictionMode); $($site.SharingAllowedDomainList); $($site.SharingBlockedDomainList)"
}
$completPath = Join-Path -Path $DestinationPath -ChildPath $filename
$content > $completPath
I would expect to be able to use the default cmdlet like this:
Connect-SPOService $adminUrl -AppId $appId -AppSecret $appSecret
You have to grant permission to the app.
Either at site collection level or at tenant level.
Grant permission at site collection level :
Open https://yourtenant.sharepoint.com/sites/yoursite/_layouts/15/appinv.aspx
Paste your cilent ID in the first field and click Lookup. It should autopopulate the otherfields
Paste the app permission request in the later field. It may vary depending on the permission you want to give. Do not forget to grant AppOnly authentication. Ex: full trust on the site collection :
<AppPermissionRequests AllowAppOnlyPolicy="true">
<AppPermissionRequest Scope="http://sharepoint/content/sitecollection" Right="FullControl" />
</AppPermissionRequests>
Grant to tenant level
Same as above, but using https://yourtenant-admin.sharepoint.com/_layouts/15/appinv.aspx
Full control in the whole tenant request is :
<AppPermissionRequests AllowAppOnlyPolicy="true">
<AppPermissionRequest Scope="http://sharepoint/content/tenant" Right="FullControl" />
</AppPermissionRequests>
I'm attempting to come up with a powershell script that would allow me to export a list of sites and subsites and the permission groups there in to a CSV.
I'm familiar with using the cmdlts but not building whole scripts.
I'm able to use:
Get-SPOSiteGroup | Export-CSV C:\...
To export site groups to a CSV but it doesn't include the name of the sites they are in.
I also found a script online that would print out the sites and subsite in my site collection here:
https://sharepoint.stackexchange.com/questions/101176/powershell-to-list-all-sites-and-subsites-in-sharepoint-online
I'm not sure how to marry the information. I'm trying to export to a CSV a list of sites and subsites and the security groups there in.
I try to run:
get-sposite | Get-SPOSiteGroup **webdite**
And get this error message:
"Get-SPOSiteGroup : The input object cannot be bound to any parameters
for the command either because the command does not take pipeline
input or the input and its properties do not match any of the
parameters that take pipeline input"
I'm not sure how to get all of this to work together.
Get-SPOSiteGroup cmdlet accepts Site parameter, so site groups per every site collection within a tenant could be retrieved like this:
Connect-SPOService -Url $adminUrl
$sitesInfo = Get-SPOSite
#Retrieve and print all sites
foreach ($site in $sitesInfo) {
Write-Host 'Site collection:' $site.Url
Get-SPOSiteGroup -Site $site.Url
Write-Host '-----------------------------'
}
To retrieve in addition groups per every web site, the following script could be utilized:
$adminUrl = "https://<tenant>-admin.sharepoint.com"
$UserName = "<username>#<tenant>.onmicrosoft.com"
$Password = "--password goes here--"
$SecurePassword = $Password | ConvertTo-SecureString -AsPlainText -Force
$creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($UserName, $SecurePassword)
$pscreds = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $userName, $SecurePassword
Connect-SPOService -Url $adminUrl -Credential $pscreds
$sitesInfo = Get-SPOSite
foreach ($site in $sitesInfo) {
Write-Host 'Site collection:' $site.Url
#1. Retrieve and print site info
#Get-SPOSiteGroup -Site $site.Url
$AllWebs = Get-SPOWebs -Url $site.Url -Credential $creds
#2.Retrieve and print webs info (groups Title property in this case)
foreach ($web in $AllWebs) {
$web.Context.Load($web.RoleAssignments.Groups)
$web.Context.ExecuteQuery()
$web.RoleAssignments.Groups.GetEnumerator() | % { Write-Host $_.Title }
}
Write-Host '-----------------------------'
}
Key points:
to retrieve webs within a site collection Get-SPOWebs.ps1 is utilized
here
to get groups per web site Web.RoleAssignments.Groups is used