I’m a new system administrator trying to learn PowerShell for some automation of repetitive tasks. I have pieced together some code I found online to handle what I’m trying to do, though it appears to be an older way.
What I’m trying to do is remotely remove Domain groups from Local groups. The script reads-in the server to connect to from a text file; reads-in the Domain groups to remove from a text file; sets the Local group on the proper server as variables; and then reports what it did in a log file, along with some output to the console just so I don’t have to read the log file.
The issue I’m having is that the Catch block continues to display, and upon further investigation, the actual error is, “Access is denied.” I read a bit about what could cause that error and it seems, to me, that the setting for accidental deletion is set which won’t allow for removal. However, when I look for solutions, it appears that the AD Cmdlets are being used to turn off accidental deletion and since I’m using an older way, I’m unsure how to update this script to fix the problem. I’d prefer the script to be updated to use the current PowerShell Cmdlets, as I’m using PowerShell ISE 4 or 5, I believe. I’m also running as an elevated user and I have access to these servers and groups. I am the administrator, after all.
Again, I’m new with PowerShell and Active Directory, and I’ve been scouring the web learning and looking for solutions. So any help with this would be much appreciated in helping me learn from this and also get the issue resolved. Thanks.
# Get List of Servers from Flat TXT file $Servers = Get-Content TestServer.txt # Get List of Domain Groups from Flat TXT file [ADSI]$DomainGroup = Get-Content NDCGroups.txt # Name the LogFile and Initialize it $LogFile = ".\Logs\test.txt" New-Item $LogFile -Type File -Force # Loop through each server $Servers | ForEach-Object { $Server = $_ Write-Output "`n$Server" Write-Output "`n-------" # Get Local Group objects $LGRemoteDesktopUsers = [ADSI]"WinNT://$Server/Remote Desktop Users,group" $LGPowerUsers = [ADSI]"WinNT://$Server/POWER USERS,group" # Remove DomainGroups from LocalRDP ForEach ( $DG in $DomainGroup ) { Try { $LGRemoteDesktopUsers.Remove( $DG.Path ) Write-Output "`nRemoved $( $DG.Path ) from $( $LGRemoteDesktopUsers.Path )" } Catch { Write-Output "`nDid Not Remove $( $DG.Path ) from $( $LGRemoteDesktopUsers.Path )" Write-Warning "Did Not Remove $( $DG.Path ) from $( $LGRemoteDesktopUsers.Path )" } } # Remove DomainGroup from PowerUsers ForEach ( $DG in $DomainGroup ) { Try { $LGPowerUsers.Remove( $DG.Path ) Write-Output "`nRemoved $( $DG.Path ) from $( $LGPowerUsers.Path )" } Catch { Write-Output "`nDid Not Remove $( $DG.Path ) from $( $LGPowerUsers.Path )" Write-Warning "Did Not Remove $( $DG.Path ) from $( $LGPowerUsers.Path )" } } } | Add-Content $LogFile