Add roles to new users automatically in subsite

To add roles to new users automatically in a subsite in SharePoint, you can use a combination of SharePoint features and PowerShell scripting. Here's a step-by-step guide to help you achieve this:

Prerequisites:

  1. SharePoint 2013 or later version
  2. PowerShell 3.0 or later version
  3. SharePoint PowerShell module (SP2013_PowerShell.exe) installed on your machine
  4. A subsite created in SharePoint

Step 1: Create a PowerShell script

Create a new PowerShell script file (e.g., AddRolesToNewUsers.ps1) and add the following code:

# Set the subsite URL and the roles to add
$siteUrl = "https://your-sharepoint-site.com/subsite"
$rolesToAssign = @("Contributor", "Reader")

# Get the SharePoint site object
$site = Get-SPSite $siteUrl

# Get the web object
$web = $site.OpenWeb()

# Get the user profile service application
$profileServiceApp = Get-SPEnterpriseSearchServiceApplication -Identity "YourProfileServiceApp"

# Get the user profile manager
$profileManager = New-Object Microsoft.Office.Server.UserProfiles.UserProfileManager($profileServiceApp)

# Loop through all new users in the subsite
foreach ($newUser in $web.SiteUsers | Where-Object {$_.IsNewUser -eq $true}) {
    # Get the user's profile
    $userProfile = $profileManager.GetUserProfile($newUser.LoginName)

    # Add the roles to the user's profile
    foreach ($role in $rolesToAssign) {
        $userProfile.AddRole($role)
    }

    # Save the changes to the user's profile
    $userProfile.Update()
}

Step 2: Configure the script to run automatically

To run the script automatically when a new user is created in the subsite, you'll need to configure the SharePoint timer job. Here's how:

  1. Open the SharePoint Central Administration site.
  2. Navigate to the "Monitoring" section.
  3. Click on "Timer Jobs" and then click on "New".
  4. Enter a name for the timer job (e.g., "Add Roles to New Users").
  5. Set the timer job to run every 15 minutes (or a schedule that suits your needs).
  6. In the "Start" section, select "Start automatically when the timer service is started".
  7. In the "Parameters" section, enter the following values:
    • ScriptName: The path to your PowerShell script file (e.g., C:\Path\To\AddRolesToNewUsers.ps1).
    • ScriptArguments: Leave this blank.
  8. Click "OK" to create the timer job.

Step 3: Test the script

To test the script, create a new user in the subsite and verify that the roles are added automatically. You can also use the SharePoint PowerShell module to test the script manually:

.\AddRolesToNewUsers.ps1

This will run the script and add the specified roles to all new users in the subsite.

That's it! With these steps, you should now have a script that adds roles to new users automatically in your SharePoint subsite.