PowerShell to Export SharePoint Sites and Subsides with security groups - powershell

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

Related

what is the PNP Power shell command equivalent to "New-Object Microsoft.SharePoint.SPFieldUserValue"

Inside SharePoint 2013 i use this command to get the username of the Created By field:-
$Approver = New-Object Microsoft.SharePoint.SPFieldUserValue($sourceweb,$ApprovalListItem["Created By"])
But in SharePoint online what is the equivalent command in PnP Power-Shell script?
Thanks
Per my test, you can try following script to retrieve username of Created By field
#Parameters
$SiteURL = "https://xxx.sharepoint.com/sites/xxx"
$ListName = "TestList"
#Connect to Source Site
Connect-PnPOnline -Url $SiteURL
$ListItems = Get-PnPListItem -List $ListName -PageSize 500 | Where {$_["FileLeafRef"] -like "*.*"}
foreach($ListItem in $ListItems){
Write-Host "Title:" $ListItem["Title"]
Write-Host "Author:" $ListItem["Author"].LookupValue
}

How to create a sharepoint site collection remotely via powershell?

How to create a new site collection remotely via Powershell
I have tried the following and all failed
Trial one:
# Create a PSCredential Object using the "User" and "Password" parameters that you passed to the job
$SecurePassword = '...............' | ConvertTo-SecureString -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential -ArgumentList "domain\user", $SecurePassword
$spms = New-PSSession -ComputerName servername -Credential $cred
$Parameters= #{
Session = $spms
ArgumentList ="siteurl","sitename",'domain\user','domain\user2'
ScriptBlock = { Param ($SiteURL,$SiteName,$SiteOwner,$SecondSiteOwner)
Add-PSSnapin Microsoft.sharepoint.powershell -ErrorAction SilentlyContinue
Function Recreate_Site_Collection ($SiteURL,$SiteName,$SiteTemplate,$SiteOwner,$SecondSiteOwner){
# Delete Site Collection
$site = get-spsite -Identity $SiteURL -ErrorAction SilentlyContinue
if($site){
Write-host "Removing the site $SiteURL" -f Red
Remove-SPSite -Identity $SiteURL -Confirm:$false
}
# Create Site Collection
Write-host "creating the site $SiteURL" -f green
echo $SiteOwner
echo $SecondSiteOwner
New-SPSite -Name $SiteName -Url $SiteURL -Template $SiteTemplate -OwnerAlias $SiteOwner -SecondaryOwnerAlias $SecondSiteOwner -Confirm:$false
}
$SiteTemplate = "DEV#0" #Developer Site Template
Recreate_Site_Collection $SiteURL $SiteName $SiteTemplate $SiteOwner $SecondSiteOwner
}}
Invoke-Command #Parameters
Error:
The user cannot be found.
however, if I run the same code on the server with the same variables it goes ok when I run the PowerShell as an admin
Trial two:
# Create a PSCredential Object using the "User" and "Password" parameters that you passed to the job
$SecurePassword = '..........' | ConvertTo-SecureString -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential -ArgumentList "domain/user", $SecurePassword
$spms = New-PSSession -ComputerName servername -Credential $cred
$Parameters= #{
Session = $spms
ArgumentList = "siteurl","sitename",'domain/user',"1033","DEV#0"
ScriptBlock = { Param ($PortalUrl,$SiteName,$userName,$LCID,$WebTemplate)
$adminSiteUrl = "centraladminurl"
$user = "user"
$pwd = '..............'
$securePwd = ConvertTo-SecureString $pwd -AsPlainText -Force
$cred = New-Object PSCredential($user, $securePwd)
$wsdlUrl = $adminSiteUrl + "/_vti_adm/Admin.asmx?WSDL"
$svc = New-WebServiceProxy -Uri $wsdlUrl -Credential $cred
$svc.Timeout = 300000 # 5 minute timeout
$svc.CreateSite(
$siteUrl, # URL
$siteTitle, # Title
$Description, # Description
$LCID, # LCID 1033 arabic
$WebTemplate, # WebTemplate
$user, # Owner Login
"user", # Owner Name
"mail",
$PortalUrl ,
"portalname"
)}}
Invoke-Command #Parameters
Error:
Exception calling "CreateSite" with "10" argument(s): "Exception of type 'Microsoft.SharePoint.SoapServer.SoapServerException' was thrown."
however, also when running the same script on the server itself with PowerShell run as admin it works with the same variables
please help
I need to automate SharePoint deployment from Jenkins which require a remotely PowerShell script and the main step is creating the site it cannot be established
It's definitely a permissions issue, but it can be kind of a pain to find. My user (the one running the script - probably your Jenkins user) was:
a local admin on the server,
listed in https://sharepointsite/ > Site Settings > Permissions > Site Collection Administrators.
but still got weird errors when running remotely:
# These commands did not work - I'm quoting the errors:
Enter-PSSession -ComputerName MySPServer
Add-PSSnapIn Microsoft.SharePoint.PowerShell
$URI = 'https://MySharePoint.domain.com'
# Can't pipe Site object to Web
Get-SPSite $URI | Get-SPWeb
'Get-SPWeb : Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))'
# Can't get SP users using web:
$web = Get-SPWeb $URI
Get-SPUser 'DOMAIN\user' -Web $web
'Get-SPUser : Cannot find an SPWeb object with Id or Url: 7aee0dc1-fe3b-4f9b-bd4b-000000000000 and Site Id: 8b662499-bb26-41ce-978e-000000000000.'
# Can't list properties of a site object
Get-SPSite $URI | fl
'Exception has been thrown by the target of an invocation.'
# Can't create a new site because the user can't be found:
New-SPSite -Url $URI -Name 'Test' -Description 'Test Site' -Template 'DEV#0' -OwnerAlias 'DOMAIN\user'
'New-SPSite : User cannot be found.'
I found that my user was not showing up as a site admin in powershell for some reason. Note that I'm running directly on the server here in order to view the users:
$URI = 'https://MySharePoint.domain.com'
$web = Get-SPWeb $uri
Get-SPUser "$env:USERDOMAIN\$env:USERNAME" -Web $web | Select UserLogin,IsSiteAdmin,IsSiteAuditor,AllowBrowseUserInfo
'UserLogin IsSiteAdmin IsSiteAuditor AllowBrowseUserInfo
--------- ----------- ------------- -------------------
DOMAIN\user False False True'
So I added myself as a site admin for my main site like so:
# Set my user as collection admin:
Get-SPUser 'DOMAIN\User' -Web $web | Set-SPUser -IsSiteCollectionAdmin:$true
# Check permissions again:
Get-SPUser "$env:USERDOMAIN\$env:USERNAME" -Web $web | Select UserLogin,IsSiteAdmin,IsSiteAuditor,AllowBrowseUserInfo
'UserLogin IsSiteAdmin IsSiteAuditor AllowBrowseUserInfo
--------- ----------- ------------- -------------------
DOMAIN\user True True True'
Get-SPSite $uri | fl UserIsSiteAdminInSystem
'UserIsSiteAdminInSystem : True'
And now all of the above commands work normally. It seems like the powershell module for sharepoint requires some access to the main webservice object in order to resolve usernames. I'm not sure what level of access is really required, but this worked for me.

Sharepoint PnP List: How to "Group by" columns using Powershell

I want to group a Sharepoint list by a column using powershell, so when users access this list, it's already grouped.
I know the List settings already has this Here, but I want to be able to control this via a powershell script that resets the list to data read from a local server.
Below images provide additional clarity of my question.
Columns not grouped together
Columns grouped together
Please take a reference of below powershell script:
#Set Variables
$SiteURL = "https://abc.sharepoint.com/sites/s01"
$ListName = "your list name"
$Username='admin#abc.onmicrosoft.com'
$Password = 'xxxx'
#region Credentials
[SecureString]$SecurePass = ConvertTo-SecureString $Password -AsPlainText -Force
[System.Management.Automation.PSCredential]$PSCredentials = New-Object System.Management.Automation.PSCredential($Username, $SecurePass)
#endregion Credentials
#Connect to PNP Online
Connect-PnPOnline -Url $SiteURL -Credentials $PSCredentials
#Get the Client Context
$Context = Get-PnPContext
#Get the List View
$View = Get-PnPView -Identity "All Items" -List $ListName
$Context.Load($View)
$Context.ExecuteQuery()
$View.ViewQuery
$ViewQuery = '<GroupBy Collapse="TRUE" GroupLimit="30"><FieldRef Name="num" /></GroupBy>' + $View.ViewQuery
#Update the view Query
$View.ViewQuery = $ViewQuery
$View.Update()
$Context.ExecuteQuery()
More references:
https://www.sharepointdiary.com/2018/04/sharepoint-online-powershell-to-update-list-view.html
https://learn.microsoft.com/en-us/powershell/module/sharepoint-pnp/get-pnpview?view=sharepoint-ps
BR

delete user from all site collections

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"

Create a Document Library from a Template using SharePoint Online PowerShell

How do I create a new document library from an existing document library saved as template using SharePoint Online PowerShell?
I was trying the following:
New-PnPList -Title "Test" -Template DocLibTemplate.stp -Url Test
I had no luck on CSOM PowerShell... PnP seemd to be the best option available.
The following PowerShell for your reference.
$ListTemplateInternalName="DocLibTemplate.stp"
$ListName ="PnpDocument"
Connect-PnPOnline -Url https://xx.sharepoint.com/sites/lz -Credential (Get-credential)
$Context = Get-PnPContext
$Web = $Context.Site.RootWeb
$ListTemplates = $Context.Site.GetCustomListTemplates($Web)
$Context.Load($Web)
$Context.Load($ListTemplates)
Invoke-PnPQuery
$ListTemplate = $ListTemplates | where { $_.InternalName -eq $ListTemplateInternalName }
if ($ListTemplate -eq $null)
{
Throw [System.Exception] "Template not found"
}
$ListCreation = New-Object Microsoft.SharePoint.Client.ListCreationInformation
$ListCreation.Title = $ListName
$ListCreation.ListTemplate = $ListTemplate
$Web.Lists.Add($ListCreation)
Invoke-PnPQuery
Disconnect-PnPOnline