简体   繁体   中英

Error while removing Users/groups from Local administrators through Powershell

I need to remove few domain users and groups from number of servers from their local administrators group , as part of a project. Since doing the same thing for many servers will consume lot of time, I was thinking to do the same through powershell. Below is the code I'm using: First, I'm trying to do it locally on one server. Once this is successfull I'll use a forloop to run it for all servers at once.

$RemoteComputer = "US05APP9008.jnj.com"
$Computer = [ADSI]("WinNT://$RemoteComputer,computer")
$Group = $Computer.PSBase.Children.Find("Administrators")
$account="domain\groupname"
$Group.Remove("WinNT://$account")   

Error Exception calling "Remove" with "1" argument(s): "A member could not be added to or removed from the local group because the member does not exist. " At C:\\Users\\admin_broy5\\Desktop\\remtest.ps1:6 char:14 + $Group.Remove <<<< ("WinNT://NA\\admin_broy5") + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : CatchFromBaseAdapterMethodInvokeTI

I tried the same through another code as well found from some other forum in stackoverflow but it also gave the same error:

$CompStat = Get-WmiObject win32_computersystem;
$Localhst = $CompStat.Name;
$Computer = [ADSI]('WinNT://'+$localhst+',computer');
$accName = [ADSI]('WinNT://NA\admin_broy5,user');
$group = [ADSI]('WinNT://'+$Localhst+'/Administrators,group');
$group.remove($accName.path);

Error: Exception calling "remove" with "1" argument(s): "An invalid directory pathname was passed " At C:\\Users\\admin_broy5\\Desktop\\rem.ps1:6 char:1 + $group.remove($accName.path); + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Kindly let me know how can I achieve my objective? Thanks in advance!!!

It does not look like anything is wrong with the commands you are using, just that they do not apply and you need to put additional code to work around them. In the first scenario, it seems that you are trying to remove a user from a group which it is not member of. That's fine, just handle the exception with try / catch.

Here is a sample function to handle the error with try / catch:

function Remove-LocalUserAccount {
     param ( [string]$userName,
             [string]$computerName = $ENV:COMPUTERNAME )



    [ADSI]$computer="WinNT://" + $computerName

    try   { $computer.delete("User",$userName) }
    catch { logmsg -msg $error -entrytype "Error"; return $false }


    return $true
}

In your case, you would use the same technique around $group.remove() as that's where you expect the error to occur:

try {
    $group.remove($accName.path);
}

catch {
   # do something, if you need to act on the error... or not
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM