Can anyone please suggest me way for below scenario:
We have domain group like “LSG-SA-Server” to provide local admin access to server. So this group needs to be added in servers local administrators group.
Suppose we have 2 groups “LSG-SA-Server1” and “LSG-SA-Server2”.
Server names are ‘Server1’ and ‘Server2’. I want to create a script that should automatically add server1 group to server1 and server2 group to server2. Can someone please guide me. I would appreciate that.
So LSG-SA-ServerX where ServerX is the server where LSG-SA-ServerX group needs admin privilege. This can be done easily if you have the list of admin groups. It can be in a file or CSV.
First, readthe file/csv
Iterate through each of them using foreach loop
Use Spit() method to split the server name, based on the pattern it will be Split("-")[-1]. The last one from the split items.
Then use Add-ADGroupMember cmdelt to add to the group.
untested example
$GroupList = Get-Conent -Path c:\temp\GroupList.txt
foreach($Group in $ServerList){
$Group = $Group.Trim() # This is to trim away leading and trailing white spaces from the file if any
$Server = $Group.Split("-")[-1]
Add-ADGroupMember -Identity $Group -Member $Server
}
Thanks for your reply. However it seems you understood this question differently. First of all, my server names also has “-” in their names so using split is not working that you mentioned above or we might have to tweak it more.
2nd, we can’t use Get-ADGroupMember because I need to add “LSG-SA-Server” group to server’s local administrators group. So either I can use Add-LocalGroupMember or if PS version is old then I can use ‘net localgroup’.
I wrote below code to get this done. I am using ‘net’ command because servers PS version is old and they don’t have Add-LocalGroupMember cmdlet on the servers.
Also ‘net’ command can’t be used if group name is more than 20 characters but I have group names with less than 20 characters so it is working fine or me. Here is my small code:
foreach ($s in $servers){
foreach($g in $groups){
if ($g -match $s){
Invoke-Command -ScriptBlock {net localgroup Administrators $using:g /add} -ComputerName $s
}
}
}