Remove a user from a group in AD using .net + powershell

0

Hello, I'm trying to remove users from a group in AD from a PowerShell script, inside an ASP.NET MVC application. I have a similar script and function to add a user in AD, but it is not working to remove users.

Here is my script and my functions: Script PowerShell:

[CmdletBinding()]
param (
    [Parameter(Mandatory=$True)]
        [String]$NomeGrupo,
    [Parameter(Mandatory=$True)]
        [String]$NomeUsuarioGrupo
)

if (!(Get-Module ActiveDirectory)) {
    Import-Module ActiveDirectory
}

$NomeGrupo = "$NomeGrupo"
$NomeUsuarioGrupo = "$NomeUsuarioGrupo"
$DomainName = "LDAP://DC=tcu,DC=gov,DC=br"


Remove-ADGroupMember -Identity $NomeGrupo -Members $NomeUsuarioGrupo

Function:

public void RemoveUser()
        {          
            foreach (log obj in db.Logs)
            {
                DateTime? _dataVencimento = DateTime.Parse(obj.DataVencimento);
                bool ts = _dataVencimento <= DateTime.Now;                               

                if (ts == true)
                {
                    using (PowerShell powershell = PowerShell.Create())
                    {
                        // Add the script to the pipeline
                        powershell.AddCommand(AppDomain.CurrentDomain.BaseDirectory + "\Powershell\Remove-User-Group.ps1");
                        // Add the parameters to the script based on the values entered by the user
                        powershell.AddParameter("NomeGrupo", obj.NomeGrupo);
                        powershell.AddParameter("NomeUsuarioGrupo", obj.NomeUsuarioGrupo);

                        try
                        {
                            // Attempt to invoke the pipeline
                            var results = powershell.Invoke();
                        }
                        catch (Exception e)
                        {
                            // Catch exception and display within validation error summary
                            ModelState.AddModelError("", "Um erro aconteceu na chamada da função" + e);
                            //return View(obj);
                        }
                        // Check for PowerShell errors - these errors will not be caught within the Try-Catch
                        if (powershell.Streams.Error.Count > 0)
                        {
                            foreach (var error in powershell.Streams.Error)
                            {
                                // Add each error to the validation error summary
                                ModelState.AddModelError("", error.ToString());
                            }

                        }
                    }                  
                } else
                {
                    // nothing to do
                }
            }
        }

Thanks in advance for your help.

    
asked by anonymous 23.10.2018 / 21:29

0 answers