Powershell provisioning new site with unique permissions but uses existing owners group - sharepoint

Currently run in to a bit of a stumbling block and i don't know if i am searching for the right thing on google to get the correct results to help me.
The situation....
1)In sharepoint via the GUI i can use unique permissions when setting up a site.
2)You are then presented with a page showing 3 possibilities(Read, Contribute and owner) of groups.
3)In these possibilities you can select to use an existing group or create a new one.
The setup i am looking for is use existing group for owner and create 2 new groups for contribute and read. How do i do this in powershell?
The other way i have thought about doing this is to not break permissions, Delete all the groups apart from the owners groups, Create 2 new groups, assign them contrbute and read and add them to the site. <- this sounds like it would work but also sounds like a workaround!
Cheers
Truez

Do you want to create custom permission levels, or custom groups but give them one of the exisiting permission levels? In the case of the former, the easiest way would be to create your custom permission levels in the GUI by copying and then modifying the existing Contribute and Read groups and then to assign these to your groups in your PowerShell script.
Here's the code you need to set your custom permissions on a site.
# Function to create role assignment variable for SharePoint group
#-----------------------------------------------------------------
Function CreateGroupRoleAssignment {
Param(
[parameter(Mandatory = $true)]
[string]
$RaName,
[parameter(Mandatory = $true)]
[string]
$GroupName
)
# Delete role assignment variable if it already exists
if(Test-Path "variable:global:$RaName") {
Write-Host "-- Removing existing Role Assignment variable: $RaName"
Remove-Variable -Name $RaName -Scope Global
}
# Create role assignment object variable in the global scope (to persist outside of the function)
Write-Host "-- Creating Role Assignment variable for SharePoint group: $GroupName"
New-Variable -Name $RaName -Value ([Microsoft.SharePoint.SPRoleAssignment] $RootWeb.SiteGroups[$GroupName]) -Scope Global
} # End Function CreateGroupRoleAssignment
# Script body
#------------
# Get your site
$Web = Get-SPWeb http://yoursiteurl
# Stop your site from inheriting permissions
$Web.BreakRoleInheritance($false)
# Create Role Definitions from the "Permission Levels" in your site
# Pick from the list in http://yoursiteurl/_layouts/role.aspx
$FullControlRD = $Web.RoleDefinitions | Where {$_.Name -eq "Full Control"}
$ContributeRD = $Web.RoleDefinitions | Where {$_.Name -eq "Contribute"}
$ReadRD = $Web.RoleDefinitions | Where {$_.Name -eq "Read"}
# Call function to create role assignments from your SharePoint site groups
# SharePoint groups inc. built-in Your Site Owners/Members/Visitors plus any you create
# See list of groups in http://yoursiteurl/_layouts/user.aspx
CreateRoleAssignment -RAName "OwnersRA" -GroupName "Your Site Owners"
CreateRoleAssignment -RAName "Group1RA" -GroupName "Your Custom Group 1"
CreateRoleAssignment -RAName "GRoup2RA" -GroupName "Your Custom Group 2"
# Bind the role definition to the role assignment to assign the desired permission level to each group
$OwnersRA.RoleDefinitionBindings.Add($FullControlRD)
$Group1RA.RoleDefinitionBindings.Add($ContributeRD)
$Group2RA.RoleDefinitionBindings.Add($ReadRD)
# Add the role assignment with the custom permission to your site
$Web.RoleAssignments.Add($OwnersRA)
$Web.RoleAssignments.Add($Group1RA)
$Web.RoleAssignments.Add($Group2RA)

I managed to find a solution.
I created the site so all the groups were inherited.
Broke inheritance
Once broken i looped through all the groups and removed any that didn't contain owner. This meant that the owner group still updated when you placed a member in the owner group at the root level site.
I then created a Members and readers group.
$businessUnitWeb = New-SPweb -Url "My Site" -Name "Test" -UseParentTopNav
$businessUnitWeb.BreakRoleInheritance($true)
$groupsToRemove = $businessUnitWeb.Groups| WHERE-OBJECT{$_.Name -ne "XXXXXXXXX Portal Owners"} | $businessUnitWeb.Groups.Remove($_)
$groupsToRemove | FOREACH-OBJECT{$businessUnitWeb.Groups.Remove($_)}
$usersToRemove = $businessUnitWeb.Users| WHERE-OBJECT{$_.Name -ne "XXXXXXXXXX Portal Owners"}
$usersToRemove | FOREACH-OBJECT{$businessUnitWeb.Users.Remove($_)}
}
$businessUnitWeb.SiteGroups.Add("$businessUnitWeb Read", $businessUnitWeb.Site.Owner, $businessUnitWeb.Site.Owner, "The read group for $businessUnitWeb")
$newGroup = $businessUnitWeb.SiteGroups["$businessUnitWeb Read"]
$newGroupAssign = New-Object Microsoft.SharePoint.SPRoleAssignment($newGroup)
$newGroupAssign.RoleDefinitionBindings.Add($businessUnitWeb.RoleDefinitions.GetByType("Reader"))
$businessUnitWeb.RoleAssignments.Add($newGroupAssign)
$businessUnitWeb.update()
$businessUnitWeb.SiteGroups.Add("$businessUnitWeb Contributor", $businessUnitWeb.Site.Owner, $businessUnitWeb.Site.Owner, "The Contributor group for $businessUnitWeb")
$newGroup = $businessUnitWeb.SiteGroups["$businessUnitWeb Contributor"]
$newGroupAssign = New-Object Microsoft.SharePoint.SPRoleAssignment($newGroup)
$newGroupAssign.RoleDefinitionBindings.Add($businessUnitWeb.RoleDefinitions.GetByType("Contributor"))
$businessUnitWeb.RoleAssignments.Add($newGroupAssign)
$businessUnitWeb.update()
Write-Host "Creating $businessAreaURL..... "
$businessUnitWeb.ApplyWebTemplate(Template stuuf")
If there are some typo's i've had to remove company tie's from the code.

Related

I need to assign users to an Azure Active Directory Group if they are members of multiple groups. Is this possible?

I have Group A, Group B and Group Collection C. I would like to only allow members into Group A if they are simultaneously a member of Group B and any group in Group Collection C
For example, User Joe Blow is a member of Group B and the third group in Group Collection C. He would be allowed into Group A.
Is this possible?
EDIT:
The answer to this question is yes, it is possible, theoretically speaking. It is supposed to be handled through Dynamic Groups.
Dynamic membership rules for groups in Azure Active Directory
However, it does not appear to work correctly for this use-case.
This query should work:
user.memberof -any (group.objectId -in ["GroupC-1Id", "GroupC-2Id"]) -and user.memberof -any (group.objectId -in ["GroupBId"])
But users who are only members Group C-1 still make it into Group A
This query has worked for others:
user.memberof any (group.objectId in ["GroupBId"]) and (user.memberof any (group.objectId eq ["GroupC-1Id"]) or user.memberof any (group.objectId eq ["GroupC-2Id"]))
But for me it causes users who are only members Group B to still make it into Group A.
I tried to reproduce in my environment in powershell:
Below are the groups that are needed to be checked.
Group 1:
Group 2:
Group 3:
I have tried the scenario using powershell , where users are added to Group-Anew when user belongs to group1 and also belongs to any one of the groups 2 and 3.
$AllUsers=Get-AzureADUser
#Add-AzureADGroupMember -ObjectId "<groupOb>" -RefObjectId "<userOb>"
$Newgroup=New-AzureADGroup -Description "TsInfoGroupNew group is for TsInfo" -DisplayName "Group-ANew" -MailEnabled $false -SecurityEnabled $true -MailNickName "TsInfoGroupNew"
$GroupAObjectId= $Newgroup.ObjectId
foreach($user in $AllUsers)
{
$userGroupMembership=Get-AzureADUserMembership -ObjectId $user.ObjectId | select displayname, description , ObjectId
$userGroupMembership
if($userGroupMembership.DisplayName -eq "group1" –and ($userGroupMembership.DisplayName -eq "group2" -or $userGroupMembership.DisplayName -eq "group3" ) )
{
$allowUsers=$user.ObjectId
#below command adds the allowed users to group Group-ANew
Add-AzureADGroupMember -ObjectId $GroupAObjectId -RefObjectId $user.ObjectId
}
}
The users are added in the expected manner after execution of the commands as required.

Azure AD Updating Bulk users from CSV

I am new to this so please apologise if I missed some information.
I have the following situation:
I have a employee list in CSV and I need to update existing users in my tenent through powershell. I tried some skripts I found online but non of them I could get working. I can connect to the tenent and import the csv but nothing more.
I need to update the following:
fax, office, streetadress, city, postalcode, department, title, officephone, mobilephone and mail
Can someone give me a template or something similar? I would really appreciate some help.
If your csv file is listed with a distinguishable object e.g. Active Directory User sAMaccount's and its correlating data 'fax, office, streetadress, city, postalcode, department, title, officephone, mobilephone and mail'
High Level Steps To Update Active Directory User Properties
Import Active Directory Module
Import CSV File containing data to be matched and updated
Run Get-ADUser cmdlet to get the object to be updated
Run Set-ADUser cmdlet to update the property
Example Script To Update AD User From CSV File
#Import Active Directory module
Import-Module ActiveDirectory
#Import CSV File to set variable for the user’s logon name + update data + delimiter
$Users = Import-CSV -Delimiter ";" -Path "c:\psscripts\users.csv"
#Using your code to filter AD Sam Accounts listed CSVData is listed with the information you wish to update
Foreach($user in $users){
#Using your code to filter AD Sam Accounts Based on column samaccountname in the csv file
Get-ADUser -Filter "SamAccountName -eq '$($user.samaccountname)'" | Set-ADUSer `
-fax $($User.Fax) `
-office $($User.Office) `
-StreetAddress $($User.StreetAddress) `
-city $($User.City) `
-postalcode $($User.PostCode) `
-title $($User.Title)`
-department $($User.Department) `
-officephone $($User.Officephone) `
-mobilephone $($User.Mobilephone) `
-mail ($User.Mail)
}
The below post shares the PowerShell script to modify bulk user attributes for multiple user accounts in a simple way by importing user details from a CSV file.
https://morgantechspace.com/2022/03/update-bulk-azure-ad-user-attributes-using-powershell.html
This script helps to update bulk user attributes as hashtable in a single command (Set-AzureADUser).
#Hashtable to keep multiple attribute values
$AttributesToUpdate = #{}
$AttributesToUpdate["JobTitle"] = "Sales Manager"
$AttributesToUpdate["Department"] = "Sales"
# Set required user attributes.
# Need to prefix the variable AttributesToUpdate with # symbol instead of $ to pass hashtable as parameters (ex: #AttributesToUpdate).
Set-AzureADUser -ObjectId "user#domain.com" #AttributesToUpdate
# Refer to the below post for more details.
# https://morgantechspace.com/2022/03/update-bulk-azure-ad-user-attributes-using-powershell.html

Route Table Details

Is there a way to fetch all details of routing from each subscription with Route-Table Name, subscriptions, next hop type address prefix.
I have tried 'Get-AzRouteTable -ResourceGroupName "" -Name "prod" | Get-AzRouteConfig | Export-Csv azureroutetable2.csv' but getting only from specific environment, is there a better way to do the same?
Regards
Devbrat
According to the help for Get-AzRouteTable it doesn't require any value to be specified for ResourceGroupName so we should just be able to loop through your available contexts. If you did have a large Azure Network infrastructure and they were logically organised by Resource Group, you may want to consider looping through Resource Groups too.
That being said, you can do something like this. It will create a csv for each subscription in your current session. Change the . at the beginning of the path value to set a full path if you would like.
$Contexts = Get-AzContext -ListAvailable
foreach ($Context in $Contexts) {
[void](Set-AzContext -SubscriptionId $Context.Subscription.Id)
$RouteConfig = Get-AzRouteTable -Name "prod" | Get-AzRouteConfig
# If you are using PowerShell 5.1, add '-NoTypeInformation' to the end of this command.
$RouteConfig | Export-Csv -Path ".\$($Context.Subscription.Name)_Routes.csv" -Encoding utf8 -NoClobber
}

How to pass specific values for Get-AzSubscription

We have a command to get all the subscriptions Get-AzSubscription | Set-Azcontext and set for that to work with multiple subscription. How do we fetch specific subscriptions from Get-AzSubscription and pass it for Set-Azcontext.
In order to do that I have tried below :
I have tried something $subscription = Get-AzSubscription -TenantId "tenant id" | where-object{$_.Name -like 'required name*'}
$subscription | Set-AzContext
Is there any better way to do the same?
Regards
Deb
There is nothing wrong with your method as long as:
You can easily write the filter clause to include all the required subscriptions. If there is no consistent naming scheme you might end up with lots of ... -or ... -or ... clauses which is messy.
You are happy that your script will automatically start to act on any new subscriptions added to your tenancy which match your filter clause.
If however:
You don't have good naming scheme so it's difficult to write a simple filter.
The script must act only on the specified subscriptions.
Then you could do this:
$subs = #('Sub 1','Live Sub','2 Test','Deb')
$subs | get-azsubscription -SubscriptionName {$_} | set-azcontext
You can use the following command to select the particular subscription you want to use :
Select-AzureRmSubscription -SubscriptionId xxxxx-xxxxx-xxxxxx-xxxx

Azure Powershell - across MULTIPLE subscriptions in an EA

I have "billing reader" access to several hundred subscriptions in an EA.
I'm trying to get a list of virtual machines and their sizes across all subscriptions.
So currently when I run a "Get-AzureRMSubscription" it shows me all the subscriptions (hundreds of them), but i'm not sure how to actually run a script against all the subscriptions?
Would be great to get a "Get-AzureRMVM" across them all
Any suggestions?
Thanks in advance!
You can possibly do something like this:
$azureSubs = Get-AzureRMSubscription
$azureSubs | ForEach-Object {Select-AzureRMSubscription $_ | Out-Null; Get-AzureRMVM -WarningAction SilentlyContinue}
You are essentially setting an array variable to hold all your Azure Subscription and piping it to the ForEach-Object cmdlet to iterate all of the objects in the array. Then you pipe it to the Get-AzureRMVM cmdlet to list all VMs in each subscription.
This is definitely not optimized for performance and there might be better solutions out there, but at least you can run it and forget it.
The reason for the Out-Null and -WarningAction is to suppress the outputs you do not need.
You didn't ask but for classic resources we have the following script run on a regular basis and its output stored in a SQL Database.
$subscriptions = Get-AzureSubscription
foreach ($sub in $subscriptions)
{
$sub | Select-AzureSubscription
Get-AzureService | % {
Get-AzureDeployment -ServiceName $_.ServiceName
} | % {
New-Object -TypeName 'PSObject' -Property #{ 'ServiceName' = $_.ServiceName; 'Addresses' = $_.VirtualIPs.Address; }
} | sort Addresses | ft
}
% is ForEach-Object, ft is Format-Table although some kind souls may come along and try to edit this and make it harder to reuse. You can add/remove properties in the select statement to tailor your output as needed. Try it in one subscription to refined your needs, then create a script to make it easy to reuse.
We recently released Azure Resource Graph to support these types of searches across multiple subscriptions. See documentation here https://learn.microsoft.com/en-us/azure/governance/resource-graph/overview

Resources