Fix deleted AD users from SharePoint

This is a small PowerShell script that will fix issues with removed SharePoint users. You may encounter problems if you remove an AD user but the later re-create it with the same AD user login. If such cases this script might help you with possible SharePoint issues. If this does not help then try to remove the user profile and run a full user profile synchronization and run the script again.

$sites = Get-SPSite

foreach ($site in $sites) {
$groups = $site.RootWeb.sitegroups
foreach ($group in $groups) {
foreach ($user in $group.users) {
# Skip All Authenticated Users, General groups
if ($user.userlogin -eq "c:0(.s|true" -or $user.userlogin -eq "c:0!.s|windows") {
if ($user.IsDomainGroup) {
# Skip Security Groups
else {
# Get user login
$splitline = $user.userlogin.split("\");
$samid = $splitline[1];
if ($user.userlogin.contains("AD domain name"))
if ($user.userlogin.contains("part of your login name")) {
Write-Host "user Found" $user.userlogin
else {
Write-Host $user.userlogin

How to change SharePoint AD group names after the group name has changed in Active Directory

Well this is simple really, The code goes through each site collection, identifies groups coming from AD, then retrieves the same group using the SID value from Active Directory and updaes the SharePoint group name based on the value in the Active Directory.

param (
 [string]$SPSiteFilter = "Your application URL",
 [string]$SPADLoginNamePrefix = "c:0+.w|",
 [bool]$UseSAMAccountName = $true

if ((Get-PSSnapin 'Microsoft.SharePoint.PowerShell' -ErrorAction SilentlyContinue) -eq $null){Add-PSSnapin 'Microsoft.SharePoint.PowerShell'}
 if (Get-Module -ListAvailable -Name ActiveDirectory) {
 Write-Host "ActiveDirectory Module exists"
} else {
 Write-Host "ActiveDirectory Module does not exist. This Script requires this module. Please check that the module is installed."
 Write-Host "To install the module through PowerShell you can use the following command:"
 Write-Host "Add-WindowsFeature RSAT-AD-PowerShell"
 Import-Module ActiveDirectory
$spWebApp = Get-SPWebApplication $SPSiteFilter
foreach($site in $spWebApp.Sites)
 Write-Host "Site: $($site.Url)"
 # Notice that the SPADLoginNamePrefix variable prefix is used to identify a AD group and also to parse the SID value
 $site.rootweb.siteusers | where { $_.IsDomainGroup -and $_.UserLogin.ToString().Contains($SPADLoginNamePrefix) } | %{
 $dispNameSplit = $_.UserLogin.ToString().Replace($SPADLoginNamePrefix, "")
 #Get the Account from AD to retrieve to correct name
 $adAccount = Get-ADGroup -Identity $dispNameSplit
 $newSPAccountDisplayName = ""
 #Modify the SharePoint Account DisplayName and Name based on the AD SamAccountName OR the Name 
 if($UseSAMAccountName -eq $true)
 { $newSPAccountDisplayName = $adAccount.SamAccountName }
 { $newSPAccountDisplayName = $adAccount.Name }
 if($_.DisplayName -ne $newSPAccountDisplayName -or $_.Name -ne $newSPAccountDisplayName)
 Write-Host "Changed SharePoint AD Group: $($_.DisplayName) to: $($newSPAccountDisplayName)"
 $_.DisplayName = $newSPAccountDisplayName
 $_.Name = $newSPAccountDisplayName
 } else
 Write-Host "SharePoint AD Group name: $($_.DisplayName) is the same as in AD : $($newSPAccountDisplayName)"
 $adAccount = $null

C# .NET Getting Windows Directory File Permissions programmatically



I while back I needed to do a security trim on files in a Windows file system based on returned search results by SharePoint search. Since in SharePoint 2010 search indexing does not know how to take into consideration file system rights for searches there was a need to do a security trimming based on what privileges you have in Active Directory and what you are given to the file itself.

Since there where alot of moving parts and hard to find out which classes and function where needed to actually do this specific task I finally found a source that gave a great sample how to do this:

Unfortunately the source above does not exist anymore for whatever reason. So for those who might need similar functionality through code here is the sample code from the link above and what you need class wise.

In the code below what you need is to call the following static function to check for if the user has certain privileges:

FileSystemRights rights = FileSystemEffectiveRights.GetRights(username, filelocation);

Then call the following function to test against the given file system privileges and what you want to user to have in the file system.
bool canReadExecute = rights.HasRights(FileSystemRights.ReadAndExecute);


Classes and enumeration needed for this functionality(there are many moving parts here and you might have to work with Active Directory and File System to test this code):

FileSystemRights Enumeration

FileSystemAccessRule Class

AccessControlType Enumeration

AuthorizationRuleCollection Class

SecurityIdentifier Class

FileSystemAccessRule Class

FileInfo Class

PrincipalContext Class

UserPrincipal Class

PrincipalSearcher Class

WindowsIdentity Class


Sample code – :

public static class FileSystemRightsEx
public static bool HasRights(this FileSystemRights rights, FileSystemRights testRights)
return (rights & testRights) == testRights;

public static class FileSystemEffectiveRights

public static FileSystemRights GetRights(string userName, string path)
if (string.IsNullOrEmpty(userName))
throw new ArgumentException(“UserName not defined!”);

//if (!Directory.Exists(path) && !File.Exists(path))
// throw new ArgumentException(string.Format(“path: {0}”, path));

return GetEffectiveRights(userName, path);

private static FileSystemRights GetEffectiveRights(string userName, string path)
FileSystemAccessRule[] accessRules = GetAccessRulesArray(userName, path);
FileSystemRights denyRights = 0;
FileSystemRights allowRights = 0;

for (int index = 0, total = accessRules.Length; index < total; index++)
FileSystemAccessRule rule = accessRules[index];

if (rule.AccessControlType == AccessControlType.Deny)
denyRights |= rule.FileSystemRights;
allowRights |= rule.FileSystemRights;

return (allowRights | denyRights) ^ denyRights;

private static FileSystemAccessRule[] GetAccessRulesArray(string userName, string path)
// get all access rules for the path – this works for a directory path as well as a file path
AuthorizationRuleCollection authorizationRules = (new FileInfo(path)).GetAccessControl().GetAccessRules(true, true, typeof(SecurityIdentifier));

// get the user’s sids
string[] sids = GetSecurityIdentifierArray(userName);

// get the access rules filtered by the user’s sids
return (from rule in authorizationRules.Cast<FileSystemAccessRule>()
where sids.Contains(rule.IdentityReference.Value)
select rule).ToArray();

private static string[] GetSecurityIdentifierArray(string userName)
// connect to the domain
PrincipalContext pc = new PrincipalContext(ContextType.Domain);

// search for the domain user
UserPrincipal user = new UserPrincipal(pc) { SamAccountName = userName };
PrincipalSearcher searcher = new PrincipalSearcher { QueryFilter = user };
user = searcher.FindOne() as UserPrincipal;

if (user == null)
throw new ApplicationException(string.Format(“Invalid User Name: {0}”, userName));

// use WindowsIdentity to get the user’s groups
WindowsIdentity windowsIdentity = new WindowsIdentity(user.UserPrincipalName);
string[] sids = new string[windowsIdentity.Groups.Count + 1];

sids[0] = windowsIdentity.User.Value;

for (int index = 1, total = windowsIdentity.Groups.Count; index < total; index++)
sids[index] = windowsIdentity.Groups[index].Value;

return sids;

Good to Know: Windows Server 2012 – Part 4

Hi this is my part four of resources for Windows Server 2012(and older ones also):

Adding a Reverse Lookup Zone
Authorize a DHCP server in Active Directory
Block Inheritance
Configure a Server Core Server with Sconfig.cmd
Configure Memory and Processors
Delegate Control of an Organizational Unit
Deploy Clustered Storage Spaces 
Deploying a GlobalNames Zone
Deploying Microsoft RemoteFX on a Single Remote Desktop Virtualization Host Server Step-by-Step Guide
Deploying Network Load Balancing (NLB) and Virtual Machines on Windows Server 2008 R2
Deployment Image Servicing and Management Command-Line Options
Enforce a Group Policy Object Link
Evaluation Versions and Upgrade Options for Windows Server 2012
Evaluation Versions and Upgrade Options for Windows Server 2012
Grant a Member the Right to Logon Locally
How to remove data in Active Directory after an unsuccessful domain controller demotion
How User Account Control Works
Hyper-V Dynamic Memory Configuration Guide
Hyper-V Virtual Switch Explained, Part 2 
Hyper-V Virtual Switch Overview
ImageX Command-Line Options
Internet Protocol Version 6 Address Space
Link a Group Policy Object
Loopback processing with merge or replace
Manage Multiple, Remote Servers with Server Manager
Managing a Server Core installation: Overview
Migrate Print and Document Services to Windows Server 2012
Operations master roles
Print and Document Services Overview
Remote Desktop Gateway Manager
Sc config
Security Tools to Administer Windows Server 2012
Set up recovery actions to take place when a service fails
Storage Pools… Dive right in!
Switching Between the GUI and Server Core in Windows Server 2012
Troubleshooting Windows Firewall with Advanced Security in Windows Server 2012
Updating root hints
Using System Configuration (msconfig)
Using the Set-Service Cmdlet
Verifying Your Basic DNS Configuration
What’s New in Hyper-V for Windows Server 2012
What’s New in Hyper-V for Windows Server 2012
Windows and GPT FAQ

Good to Know: Windows Server 2012 – Part 3

Here is my newest sources of knowledge to Windows Server 2012 Administration:

Access-based Enumeration
Active Directory Service Interfaces
Active Directory-Integrated DNS Zones
AD DS Installation and Removal Wizard Page Descriptions
Adding Disks to the Storage Pool
Configure Memory and Processors
Configuring Pass-through Disks in Hyper-V
Configuring the Minimal Server Interface
Create a Rule for Packaged Apps
Create a Spanned Volume
Delegate Control of an Organizational Unit
Desktop Experience Overview
DHCP Scopes
DHCP Tools and Options
DHCP: The server should be configured to send its default gateway to all clients
Enable and Configure MAC Address Filtering
Features Removed or Deprecated in Windows Server 2012
FSMO placement and optimization on Active Directory domain controllers
Group scope
Group types
How manage Published (a.k.a Metro) Apps in Windows 8 using Group Policy
How to configure a connection to a virtual private network (VPN) in Windows XP
How to create and delete hidden or administrative shares on client computers
How to create the Central Store for Group Policy Administrative Template files in Windows Vista
How To Remove the Root Zone (Dot Zone)
How to View Printer Objects in Active Directory
Hyper-V Virtual Fibre Channel Overview
Install a New Windows Server 2012 Active Directory Forest
Installing AD DS by using Server Manager
Installing Windows Server 2012
Local Users and Groups Extension
Managed-By attribute
Net services commands
Netsh Technical Reference
NIC Teaming Overview
Remote Management with Server Manager
Restricted Groups
Restricted Groups 
Securing DNS zones
Storage Spaces Overview
To rename the Administrator account using the Group Policy Management Console
Understanding AppLocker Rules
Using WinRS
Verifying Your Basic DNS Configuration
What’s New in Hyper-V for Windows Server 2012
Which ports do you need to open on a firewall to allow PPTP and L2TP over IPSec VPN tunnels?–46811
Viewing advanced settings in Active Directory Users and Computers
Windows PowerShell 3.0 and Server Manager Quick Reference Guides
Windows Server 2008 R2 and Windows Server 2008
Windows Server Installation Options
Work with Software Restriction Policies Rules

SharePoint Forms Based Authentication against Active Directory with password change


In this post I am going to guide you through the steps necessary to setup a FBA against AD with the possibility to change your password. I will not write a step by step instructions how to do it BUT based on what I had to fight and solve I will post the best possible ways to do these steps to my knowledge:

1. The first step to do is to to configure your existing web application(or create a new one) to support claims authentication and to follow the steps to configure the AD support for the forms authentication.

Configure forms-based authentication for a claims-based web application in SharePoint 2013:

Migrate from classic-mode to claims-based authentication in SharePoint 2013:

Also for SQL Server Authentication if needed:

2. The second step is to create a custom sign in page to apply custom logic to the authentication phase like changing the password of a user:

A few examples how to do it:

3. The third step is to create the custom code to change the user password:

What you need to do:

An Active Directory user with delegated privileges to the OU or CN where the authenticated users reside. This user must have the privileges to reset and change passwords.

Make use of Secure Store Service in SP2010 to store the AD account and other information securely. Notice: When accessing the Secure Store Service from the sign in page the user that will be accessing the SSS is anonymous user. So what you need to do is to use SPSecurity.RunWithElevatedPrivileges delegate.

Implement the custom .NET code to change the password with impersonation so get access to the AD(notice that the user which runs the code is anonymous)

NOTICE: I had problems using another set of .NET class and function to perform the change password trough code. Problems with authorization against AD:

4. Bonus: How to get rid of the Mixed authentication selection page for internal users of the web application.

When you access a SharePoint application that has both Forms and Windows Authentication enabled for the application SharePoint will ask the users to select which authentication to use. This is not necessarily what you want internal users to see. Most probably the functionality required is so that the internal users logs in normally as if it is an intranet website.

The following code below is meant to be used for internal users who are not accessing the site through the forms sign in page. What you need to is to create a custom httpmodule and in the handler code below identify under which page you are and based on that to directly redirect the user to the front page of the website without asking users to choose which authentication method to use. Sample code(not the best but does the trick 🙂 ):

static void context_PreRequestHandlerExecute(object sender, EventArgs e)


            HttpApplication httpApp = sender as HttpApplication;

            HttpContext context = httpApp.Context;

            string httpUrl = context.Request.Url.ToString().ToLower();

            var page = HttpContext.Current.CurrentHandler as Page;

            string previousPageUrl = context.Cache[CacheKey_LoginStatus] as String;

            String intranetURL = System.Configuration.ConfigurationManager.AppSettings[“authentication page in sharepoint app setting value, this is sharepoint specific sample(modify for your environment): http://localhost:46752/_windows/default.aspx?ReturnUrl=/_layouts/Authenticate.aspx?Source=/_windows/default.aspx&amp;Source=/_windows/default.aspx “%5D ?? null;

            Uri httpUrlURI = new Uri(httpUrl);

            String localhostCalculated = httpUrlURI.AbsoluteUri.Replace(httpUrlURI.PathAndQuery, String.Empty);



                if (context.Request != null && String.IsNullOrEmpty(intranetURL) == false)


                    if (httpUrl.Contains(“/_layouts/closeconnection.aspx?loginasanotheruser=true”))


                        context.Response.Cookies.Add(new HttpCookie(CacheKey_LoginStatus, “true”));


                    if (httpUrl.Contains(“/_layouts/signout.aspx”))


                        context.Response.Cookies.Add(new HttpCookie(CacheKey_LoginStatus, “true”));


                    bool isSignOut = false;

                    Boolean.TryParse(context.Response.Cookies[CacheKey_LoginStatus].Value, out isSignOut);

                    if (isSignOut)



                        context.Response.Redirect(ConfigurationManager.AppSettings[“redirect page to somewhere else than the application app settings value this can be any page you want”]);


                    else if (httpUrl.Contains(localhostCalculated + “/_login/default.aspx”))






            catch (Exception Ex)



            if (page == null) return;

            page.PreInit += page_PreInit;


OR you could do something like the following link where you do a IP based functionality:

Possible problem areas – Good to know:

Office documents:

Authentication requests when you open Office documents:
How documents are opened from a Web site in Office 2003:

For Juniper VPNs:

[SSL VPN] Known Issues and limitations when accessing Microsoft SharePoint 2003 / 2007 / 2010 resources via the Web Rewrite Access mechanism:

[SSL VPN] Supported features and functionality of SharePoint 2010 when accessed via Secure Access SSL VPN’s Web/Rewrite access method:

Changing Active Directory user passwords in a .NET Web Application

Here are some tips on how to allow your web application to change passwords to Active Directory. There are several ways which all work in a similar but different way. This is one of them and what you need to take into consideration.

Here I will concentrate in the code logic and configurations what you need to take and do.

These are the following steps you need to take:

1. Create a web form for you password reset

2. Create a account with just enough privileges to set or reset user passwords

3. Impersonate this account and reset or set a new password under this password “admin” account

And a small sample code on how to change a password:

using (var context = new PrincipalContext(ContextType.Domain, “domain”, “username”, “password”))


     using (var user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, “username whose password to change”))



//// or

                                    //user.ChangePassword(“oldPassword”, “newpassword”);