Esempio n. 1
0
        private TargetElement GetMatchingTargetOrNull(ComputerPrincipal computer)
        {
            List <TargetElement> matchingTargets = new List <TargetElement>();

            foreach (TargetElement target in LapsConfigSection.Configuration.Targets.OfType <TargetElement>())
            {
                if (target.Type == TargetType.Container)
                {
                    if (Directory.IsPrincipalInOu(computer, target.Name))
                    {
                        logger.Trace($"Matched {computer.SamAccountName} to target OU {target.Name}");
                        matchingTargets.Add(target);
                    }

                    continue;
                }
                else if (target.Type == TargetType.Computer)
                {
                    ComputerPrincipal p = Directory.GetComputerPrincipal(target.Name);

                    if (p == null)
                    {
                        logger.Trace($"Target computer {target.Name} was not found in the directory");
                        continue;
                    }

                    if (p.Equals(computer))
                    {
                        logger.Trace($"Matched {computer.SamAccountName} to target computer {target.Name}");
                        return(target);
                    }
                }
                else
                {
                    GroupPrincipal g = Directory.GetGroupPrincipal(target.Name);

                    if (g == null)
                    {
                        logger.Trace($"Target group {target.Name} was not found in the directory");
                        continue;
                    }

                    if (Directory.IsPrincipalInGroup(computer, g))
                    {
                        logger.Trace($"Matched {computer.SamAccountName} to target group {target.Name}");
                        matchingTargets.Add(target);
                    }
                }
            }

            return
                (matchingTargets.FirstOrDefault(t => t.Type == TargetType.Computer) ??
                 matchingTargets.FirstOrDefault(t => t.Type == TargetType.Group) ??
                 matchingTargets.FirstOrDefault());
        }