1
Hello, I am trying to remove users from a group in AD from a Powershell script, within an Asp.net MVC application. I have a similar script and function to add a user in AD, but the removal of users is not working.
Follow 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
}
}
}
From now on, I appreciate all your help.
And what’s the mistake?
– Leandro Angelo
The system shows no error, only users remain in the group within AD.
– gustavomn
And running straight from powershell?
– Leandro Angelo
Running straight from powershell works.
– gustavomn
is not permission level? type opens PS as Admin, but in the application is using an account without this upgrade?
– Leandro Angelo
I am running visual studio as administrator, with the same account I run powershell. And the function of adding a user to an AD group works by visual studio.
– gustavomn