I need to add the computer to the Event Log Readers group. I had tried the below script.
$hostName = "Hostname"
$computername = $env:computername
$EventLogGroup = [adsi]"WinNT://$computername/Event Log Readers,group"
$temp = "WinNT://$hostName"
$EventLogGroup.Add($temp)
The same script worked for adding the user to group and for adding the computers its not adding.
Object types we need to change to Computers I think. Locations will be in same domain.
Any modifications or alternative script will be helpful
"A member could not be added to or removed from the local group because the member does not exist" this is the error I am getting while executing the script
Try to add the domain name and a dollar sign after the computer name:
$temp = "WinNT://DomainName/$hostName$,computer"
Related
i'm trying to develop a script that remove a domain user from local administrators group (i can use computer management from ad but its a graphical interface i need to do it with commands) for now i'm using invoke command to remotely connect to machines and remove their users from local admins group .
im using this command : Invoke-Command -ComputerName $line2.split(";")[0] -ScriptBlock { net localgroup "administrators" $using:notadmin /DELETE } -Credential $Cred
the problem here if a the machine is not online i need to wait until it will be online , i'm searching how to remove users from local group (administrators for example ) through ad
is there a command to do that ?
I see two approaches:
If you would like to use Group Policy, you may check for: Restricted groups.
https://www.petri.com/manage-local-active-directory-groups-using-group-policy-restricted-groups
Another option would be to incoroporate Test-Connection in your script, validating if computer is online. If it is - execute the script, if it is not, store it in another list with offline machines.
Then later run the script against the offline machine list ... and so on until all the computers are being covered.
P.S. And yes, as suggested in the commments, consider using remove-localgroupmember, if your powershell version support it.
Again, depends of the case.
Hope it helps!
$RemoteComputer = "yourComputer"
$Computer = [ADSI]("WinNT://$RemoteComputer,computer")
$Group = $Computer.PSBase.Children.Find("Administrators")
ForEach ($User in (Get-Content
"c:\users\administrator.domain\desktop\localadmin.txt"))
{ $Group.Remove("WinNT://$User")
}
i tired this code and it really helped me thnx for help
Trying to create a powershell script to perform the following tasks:
- Asks for a username to use when creating folder and assigning permissions
- Create folder on our NAS with that username for a name
- Create DFS folder with same name and assign it a target path
- Assign explicit permissions for the user to that DFS folder
My script looks like the following:
$Username = read-host "Type Username"
#Create new folder on the NAS and set necessary permissions
New-Item -Path \\NAS\USER_SHARE\$Username -ItemType Directory
#Create new DFS folder and target
New-DfsnFolder -Path "\\DOMAIN.local\user\$Username" -TargetPath "\\NAS\USER_SHARE\$Username"
#Assign explicit permissions to DFS folder for user
dfsutil property SD grant \\DOMAIN.local\user\$Username DOMAIN\$Username:F protect
It performs everything but the last line. It creates the DFS folder but doesn't give permissions. No error message is given, just prints out the help info for the dfsutil command. When I run the last line independently with a static username, it is successful. So I believe there is something with the syntax of the $Username:F part of that last line of code messing it up.
How can I separate that last section to make this work?
Try the invoke operator: &. Also, your variable call to $Username is going to cause issues with the colon, so you want to use {} around the variable name.
$Params = #('property','SD','grant',
"\\DOMAIN.local\user\$Username",
"DOMAIN\${Username}:F",
'protect')
& dfsutil #Params
Now, before I start, I will let you in on a secret: this is on a Domain Controller.*
*The above statement is stricken due to irrelevance as the only significant change that occurs to the Local Administrator account and the Local Administrator Group (within the context and scope of this question) is minimal and doesn't alter the outcome enough to require differentiation.
I didn't have this kind of trouble on any of the other servers and I am willing to bet that the reason behind it is because it is on a DC.*
*Same reason as stated above. The accepted answer explains the inconsistency and was an oversight on my part, not the architecture (read features) of Windows Security or Domain Controllers.
I have been playing around with a few ideas on how to check if a script has been called from an account that is either the local Administrator or, at the very least, called by an account that is part of the Local Administrators group.
I have renamed the local Admin account, however, I know that I can see if the script has been called by local Admin account by typing:
(New-Object System.Security.Principal.NTAccount('reserved')).Translate([System.Security.Principal.SecurityIdentifier]).Value
and I can see if the SID ends in -500.
The problem occurs when I run a condition to see if the calling account is part of the Administrators group (which is a larger scope) by typing:
PS> [bool](([System.Security.Principal.WindowsIdentity]::GetCurrent()).Groups -match "S-1-5-32-544")
PS> False
A quick check to see what account it was using:
PS> $env:username
PS> reserved
or the needlessly complicated way (though I prefer it sometimes):
PS> Write-Host ((Get-WmiObject Win32_Account | ?{$_.SID.Substring($_.SID.Length-4,4) -eq '-500'}).Caption).Split("\",2)[1] -fore GREEN
PS> reserved
and I even type:
PS> net user reserved
where it tells me Local Group Memberships *Administrators.
I pull up ADUC (dsa.msc) and I look in the Builtin container and double-click on the Administrators group. I select the Members tag and lo, and behold, reserved is actually a member!
So, a recap:
By typing net user reserved, I was able to verify it was part of the Local Administrators group
I looked in ADUC and verified reserved was a member of the builtin Administrators group
I ensured reserved was indeed the Local Administrator account by verifying the SID started with S-1-5... and ended with ...-500
To take it a step further, I made sure the SID matched the Active Directory Group named "Administrators" by typing Get-ADGroup -Identity "Administrators". I then typed Get-ADGroupMember -Identity "Administrators" and made sure reserved was listed (it was AND the SID matched!).
When I check to see if the well-known Administrators Group SID is found in the Groups of that account (by getting the current Windows Identity), it says that it isn't.
What gives?
Why do I get every indication that it actually is a member of the Local Administrators group but that SID isn't found in the account's groups?
When a computer is promoted to a domain controller, there are no more local users or groups on the machine. Member computers have local users and groups, and can also use domain users and groups for authentication, but on a DC, there are only domain objects.
See also: https://serverfault.com/a/264327/236470
I happened to stumble across something and I realized the answer to this question. For the sake of those that come here looking for assistance, here is the answer to my question:
Very simply--in regards to Powershell--if the Administrator Group SID (S-1-5-32-544) does not show up in the Groups of the user, that is a first-line indication that the script is not running with Administrative credentials.
For example, when I type out:
([Security.Principal.WindowsIdentity]::GetCurrent()).Groups
and I do not see the Administrator Group SID listed even though I know for a fact that the account I am signed into is a member of the Administrator Group, it means the current Powershell process does not have Administrative credentials.
If you click Run As Administrator and type the same as above, you will see that it lists the Administrator Group SID in Groups.
The reason why I was experiencing the inconsistency is simply because I was not running the Powershell process as an Administrator.
So, in short, there are a few ways you can check to verify if your current Powershell session has Administrator credentials. The first one is found in countless websites around the internet and is very common (I did not write this one):
$myWindowsID = [Security.Principal.WindowsIdentity]::GetCurrent()
$myWindowsPrincipal = New-Object Security.Principal.WindowsPrincipal($myWindowsID)
$adminRole = [Security.Principal.WindowsBuiltInRole]::Administrator
if($myWindowsPrincipal.IsInRole($adminRole)) {
\\ TODO: Process is running as Administrator
Clear-Host
} else {
$newProcess = New-Object System.Diagnostics.ProcessStartInfo "Powershell"
$newProcess.Arguments = "& '" + $script:MyInvocation.MyCommand.Path + "'"
$newProcess.Verb = "runas"
[System.Diagnostics.Process]::Start($newProcess)
exit
}
Here is another way (I did write this one):
[Security.Principal.WindowsIdentity]::GetCurrent() | %{
if($_.Groups -contains "S-1-5-32-544") {
\\ TODO: Process is running as Administrator
Clear-Host
} else {
Start Powershell -ArgumentList "& '$MyInvocation.MyCommand.Path'" -Verb runas
exit
}
}
# The Foreach-Object (%) could be replaced with another pipeline filter
I see a lot of people asking this question and because of Powershell appealing to many Systems Administrator (especially ones without a background in programming), I really think this will come in handy for others down the line.
I'm just a junior programmer, just started with programming and because my work requests me to create some handy powershell scripts I was wondering if you can help me with a particular one.
We have a lot of customers with a lot of servers. When they are newly installed I do check them and after that we do regular maintenance. Because each customer has several servers with different roles I want to have the "Computer" icon on my desktop.
I can do that by clicking start -> rightclick Computer -> Enable "Show on Desktop"
Furtheron I want to have this Computer icon renamed to the hostname (because the hostname tells me it's role in the domain)
Now my goal is to create a powershell script that creates this computer icon with hostname for all the server in the domain.
I've tried to search my way to the usual search engines and came up with this:
1) Locate with regedit [HKEY_CLASSES_ROOT\CLSID\{20D04FE0-3AEA-1069-A2D8-08002B30309D} rename LocalizedString to LocalizedString.Old
2) Now switch to Regedit32 Create a new VALUE type Expand_SZ name it LocalizedString On XP and Windows 2000 with SP3 replace LocalizedString with %Username% at %Computername%
Which isn't suitable because we use W2K8R2SP1 servers.
After that I ended up with this script:
$ComputerName = "Localhost"
$Hive = "CurrentUser"
$Key = "Software\Microsoft\Windows\CurrentVersion\Explorer\HideDesktopIcons\NewStartPanel"
$MyComputer = "{20D04FE0-3AEA-1069-A2D8-08002B30309D}"
$UserFiles = "{59031a47-3f72-44a7-89c5-5595fe6b30ee}"
$Kind = [Microsoft.Win32.RegistryValueKind]
$RegHive = [Microsoft.Win32.RegistryHive]$hive
$RegKey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey($RegHive,$ComputerName)
$MyComputerValue = ($RegKey.OpenSubKey($Key)).GetValue($MyComputer)
$UserFilesValue = ($RegKey.OpenSubKey($Key)).GetValue($UserFiles)
if ($MyComputerValue -eq $null -or $MyComputerValue -eq 0)
{
$Computer = $regKey.OpenSubKey($RootKey,$true)
$Computer.SetValue($MyComputer, 1,$Kind::DWord)
}
if ($UserFilesValue -eq $null -or $UserFilesValue -eq 0)
{
$User = $regKey.OpenSubKey($RootKey,$true)
$User.SetValue($UserFiles, 1,$Kind::DWord)
}
This doesn't seem to be doing anything at all.
I know this registry key is used for the computer on desktop:
“{20D04FE0-3AEA-1069-A2D8-08002B30309D}”=dword:00000000
Continued search...
So I found this:
To show the ‘My Computer’ icon on the desk"text-decoration:underline;">
[HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\HideDesktopIcons\NewStartPanel]
Name = {20D04FE0-3AEA-1069-A2D8-08002B30309D}
Type =REG_DWORD
Value = 0
To change the ‘My Computer’ icon to computer or user name:
[HKCR\CLSID\{20D04FE0-3AEA-1069-A2D8-08002B30309D}]
Name = LocalizedString
Type = REG_EXPAND_SZ
Data value = %computername% or any combination you like – eg %username% %computername%
However the second part keeps giving me an error and even if i can get it to work, i want to run the script onces and all servers in domain should be having this update.
Thanks for helping out.
Best regards,
Nick
Changing HKCR\CLSID\{20D04FE0-3AEA-1069-A2D8-08002B30309D}\LocalizedString is still suitable on Server 2008 R2, but you need to take ownership of the key and grant administrators full access to it first.
As part of my current role, I frequently find myself having to work with objects in one of my organisation's resource forests. At the moment in order to do that, I use an RDP session connected to a server within that forest, and authenticate to it with a specific "Admin" account in that forest.
I'm starting to find this tedious, and so I've been trying to come up with a nice profile.ps1 which will get me a DirectoryEntry for the resource forest that I can work on with Powershell (v2.0) on my local workstation instead, and save me the tedium of constantly re-establishing RDP sessions.
So I've got some code in my profile.ps1 which looks like this:
$resforest = "LDAP://DC=ldap,DC=path,DC=details"
$creds = Get-Credential -credential "RESOURCE_FOREST\my_admin_account"
$username = $creds.username
$password = $creds.GetNetworkCredential().password
$directoryentry = New-Object System.DirectoryServices.DirectoryEntry($resforest,$username,$password)
All of this proceeds fine, however, when I come to actually use the entry thus:
$search = New-Object DirectoryServices.DirectorySearcher($directoryentry)
$search.filter = "(&(anr=something_to_look_for))"
$search.findall()
I get a logon failure.
Now, I know the credentials are fine, I can map drives with them from my workstation to machines in the resource forest - and that works fine - so what am I ballsing up here?
PS - Please don't ask me to do anything with Quest's AD cmdlets - they're not allowed here.
Turns out the issue was with the serverless binding I was attempting to do.
If I modify the LDAP path to "LDAP://ldap.path.details/DC=ldap,DC=path,DC=details" then everything works.
Thanks for everyone who at least looked at the question ;)