I want to know if a user whom username is delivered is member of a group whom groupname is delivered.
$u = Get-WmiObject -Class Win32_UserAccount -Filter "Name='$username'"
$g = Get-WmiObject -Class Win32_Group -Filter "Name='$groupname'"
So I get two object with the property SID.
How can I check that user $u is member of group $g?
You can do this with an Associators query (example). Which are notoriously slow but do work.
$u = Get-WmiObject -Class Win32_UserAccount -Filter "Name='user'"
$group = Get-WmiObject -Class Win32_Group -Filter "Name='group'" | Select-Object -ExpandProperty Caption
$u | foreach {
$query = “Associators Of {Win32_UserAccount.Domain='” `
+ $_.Domain + “',Name='” + $_.Name `
+ “'} WHERE AssocClass=Win32_GroupUser”
$memberOf = Get-WmiObject -Query $query |
select -ExpandProperty Caption
If($memberOf -contains $group){
Write-Host "$($_.Name) is a member of $group"
} Else {
Write-Host "$($_.Name) is not a member of $group"
}
}
Get the use you are looking for and group your are checking to see if the user is a member of. While u$ should be only one user it is still a collection with one member. Pipe it into a ForEach-Object and build the Associators query. Execute the query and return all the group captions ( domain\groupname). Since $memberof is an array we can use -contains to see if the group you are looking for is there.
Alternatively
You could use the AD cmdlets if you have access to them and run the following
(Get-ADUser $user -Properties memberof | Select-Object -ExpandProperty memberof) -contains (Get-ADGroup -Identity $group)
The above will return True or False. You can install Ad cmdlets by using import-module activedirectory
Continued Testing
OpenLDAP should support this from what I gather and it's much faster then the previous WMI.
$search = [adsisearcher]"(&(objectcategory=user)(Name=userFullName))"
$userLDAP = $search.FindOne().Path
$userMembers = ([ADSI]$userLDAP).memberof
$search = [adsisearcher]"(&(objectcategory=group)(Name=groupname))"
$group = ($search.FindOne().Path) -replace "LDAP://"
$userMembers -contains $group
Sorry as I do not have access to OpenLDAP for testing. Do a search for a user and get the MemberOf as $userMembers. Then get the group into $group. Needed to remove the LDAP prefix from the string. Then just do another -Contains again.
Related
I am trying to scan computers in a specific OU in my AD to get the activation status of Windows.
I keep getting
Test-Connection : Testing connection to computer 'CN=PCNAME,OU=MY-OU' failed: No such host is known
although when i try to test the command against a single remote PC, it works fine getting the output
I tries getting all hosts using
$Hosts = Get-ADComputer -Filter \* -SearchBase "OU=MY-OU"
and then ran a for loop to test the connection of each host and using
foreach ($PC in $Hosts) {
if (Test-Connection $PC -Count 1) {
$License = Get-CimInstance SoftwareLicensingProduct -Filter "Name like 'Windows%'" -ComputerName $PC |where { $_.PartialProductKey } | select Description, LicenseStatus
$csv = [PSCustomObject]#{
License = $License
Computername = $PC
}
}
}
Write-Output $csv
Currently your $PC value is like this
$PC = "CN=server1,OU=OU1,OU=OU2,OU=OU3,DC=domain,DC=org"
in order to get computer name, split the string like below and use that value for test-connection
$CN = $PC.Split(',')[0].Split('=')[1]
$domainName = "CN=server1,OU=OU1,OU=OU2,OU=OU3,DC=domain,DC=org"
$CN = $domainName.Split(',')[0].Split('=')[1]
$CN
Edited: There are multiple properties in $Hosts, so instead of splitting distinguished name, use Select-object to get dns hostname.
I do not have an environment to test this code.. so please try yourself.
$Hosts = Get-ADComputer -Filter \* -SearchBase "OU=MY-OU" | Select-Object dnsHostName
$csv = foreach ($dnsHostName in $Hosts) {
Write-Output $dnsHostName
if (Test-Connection $dnsHostName -Count 1) {
$License = Get-CimInstance SoftwareLicensingProduct -Filter "Name like 'Windows%'" -ComputerName $dnsHostName | where { $_.PartialProductKey } | select Description, LicenseStatus
[PSCustomObject]#{
License = $License
Computername = $dnsHostName
}
}
}
$csv | Export-csv -Path C:\temp\output.csv -NoTypeInformation
I'm doing a virtual machine test, I have the following dilemma.
I want to modify a field to users who have HomeDirectory configured, for a new DFS path.
I have this script I does not work:
$user = Get-ADUser -Filter {HomeDirectory -like '*'} -Properties HomeDirectory | Select-Object samaccountname
Set-ADUser -Identity $user -Replace #{homeDirectory="\\\mboulaayoun.com\comu\personals\$user"}
Hi guys finnaly i get the correct way o do this, i hope can help someone with the same o similar problem.
$user = Get-ADUser -Filter {HomeDirectory -like '*'} -Properties HomeDirectory, HomeDrive
foreach($e in $user)
{
$name= $e.SamAccountName
$drive = $e.HomeDrive
Set-ADUser -Identity $name -HomeDirectory \\mboulaayoun.com\comu\personals\$nom -HomeDrive $drive
}
GOAL: Obtain a CSV file with the following information:
Computer Name
Share Name
Share Path
Share Description
for all non-admin (type 0) SMB shares on all servers from a list (txt file).
INITIAL CODE:
param (
[Parameter(Mandatory=$true,Position=0)]
[ValidateNotNullOrEmpty()]
[String]
$path
)
$computers = Get-Content $path
$shareInfo = #()
ForEach ($computer in $computers) {
$shares = gwmi -Computer $computer -Class Win32_Share -filter "Type = 0" | Select Name,Path,Description
$shares | % {
$ShareName = $_.Name
$Props = [ordered]#{
Computer = $computer
ShareName = $_.Name
Path = $shares.Path
Description = $shares.Description
}
}
$ShareInfo += New-Object -TypeName PSObject -Property $Props
}
$shareInfo | Export-CSV -Path .\shares.csv -NoType
CODE OUTPUT:
"Computer","ShareName","Path","Description"
"SERVER1","SHARE1","System.Object[]","System.Object[]"
"SERVER2","SHARE12","System.Object[]","System.Object[]"
"SERVER3","SHARE3","System.Object[]","System.Object[]"
PROBLEM:
While the code provides output for each server, it seems to not include all shares from the servers. Furthermore, the Path and Description fields are not populated with good information.
ADDITIONAL INFO:
The code:
$shares = gwmi -Computer $computer -Class Win32_Share -filter "Type = 0" | Select Name,Path,Description
Produces good information as below:
Name Path Description
---- ---- -----------
print$ C:\WINDOWS\system32\spool\drivers Printer Drivers
Share D:\Share
SHARE2 D:\SHARE2
Software C:\Software The Software
$shares | % {
$ShareName = $_.Name
$Props = [ordered]#{
Computer = $computer
ShareName = $_.Name
Path = $shares.Path
Description = $shares.Description
}
}
You're using $shares instead of $_ for the Path and Description properties, so each of these properties is assigned a list of the values of the respective property of each element of the $shares collection.
Also, why are you building custom objects in the first place when you just need to filter the WMI query results? The computer name can be obtained from the __SERVER (or PSMachineName) property. Plus, type 0 means a shared disk drive, not an administrative share. You need to filter the latter by other criteria (usually description and/or share name).
$filter = "Type = 0 And Description != 'Default Share' And " +
"Name != 'ADMIN$' And Name != 'IPC$'"
$computers |
ForEach-Object { Get-WmiObject -Computer $_ -Class Win32_Share -Filter $filter } |
Select-Object #{n='Computer';e={$_.__SERVER}}, Name, Path, Description |
Export-Csv -Path .\shares.csv -NoType
Is there any way to get list of all local user accounts on a remote computer via Powershell?
You can get this with a WMI-query.
function Get-LocalUser ($Computername = $env:COMPUTERNAME) {
Get-WmiObject -Query "Select * from Win32_UserAccount Where LocalAccount = 'True'" -ComputerName $ComputerName |
Select-Object -ExpandProperty Name
}
Get-LocalUser -ComputerName "TestPC1"
My goal is to get a list of AD computer objects not following naming conventions with the whenCreated property. I am trying to export out a HTML file using the following PowerShell function:
function get_bad_names
{
$result = Get-ADComputer -searchbase $OU
-Filter {Name -notlike 'name1' -and
Name -notlike 'name2' -and
Name -notlike 'name3'}
-Properties whenCreated | sort whenCreated
$result | ConvertTo-Html | Out-File $dir\badnames.html
}
get_bad_names
Is there a more elegant way of structuring the Name filter lines? We have over 40 lines of different "names." In other words, over 40 lines in my script say Name -notlike 'name#' -and
Ideally I'd like for the code to read from a text file and export out the same results.
FYI: this function works but it is not ideally written. Any suggestions would be appreciated.
If you'd like to filter the query, construct an LDAP filter:
# Define the names to exclude
$NamesToExclude = "Name1","Name2","Name3"
# Turn them into LDAP clauses in the form of "(!(Name=Name1))"
$LDAPClauses = $NamesToExclude |ForEach-Object {
'(!(Name={0}))' -f $_
}
# Create a single query filter string with all the clauses from above
$LDAPFilter = "(&$LDAPClauses)"
$result = Get-ADComputer -LDAPFilter $LDAPFilter -SearchBase $OU -Properties whenCreated |Sort-Object whenCreated
You could filter with a regular expression using Select-Object but then you should get all computers in the OU with the -filter *, and that might strain your network. I would do the filtering and if more properties are needed, run Get-Computer again only for the matches:
Get-ADComputer -searchbase $OU -Filter * |
? { $_.name -match "name\d{1,2}" } | # Match if string "name" is followed one or two digits
Get-ADComputer -property * # Get all properties for the computers if needed
Is there a more elegant way of structuring the Name filter lines?
Not exactly. You have a fairly limited set of operators when you use the -Filter parameter of commands in the ActiveDirectory module because it has to translate them all to LDAP filters.
However, you can do something like this:
$ExcludedPatterns = 'Name1', 'Name2', 'Name3'
$ComputerFilter = foreach ($Pattern in $ExcludedPatterns) { "(Name -notlike '$Pattern')" }
$ComputerFilter = $ComputerFilter -join ' -and '
Get-ADComputer -Filter $ComputerFilter
Now you can maintain a list of name patterns.
Keep in mind that the -Filter property is not a ScriptBlock on the ActiveDirectory commands. They're all Strings and in spite of the documentation for these commands they should be written that way. Writing them as ScriptBlocks will eventually cause you problems with variable expansion.
Compare:
$ComputerName = hostname
Get-ADComputer -Filter "Name -eq '$ComputerName'"
Get-ADComputer -Filter { Name -eq '$ComputerName' }
Thank you to everyone for their feedback. I was impressed how fast the responses were.
I was able to achieve my goal using regular expressions reading from a text file.
My code now looks like this:
[regex]$Expression = Get-Content $dir\regex.txt
function get_bad_names
{
$result = Get-ADComputer -searchbase $OU
-Filter {Enabled -eq $true}
-Properties whenCreated | Where-Object {$_.Name -notmatch $Expression}| sort whenCreated
$result | ConvertTo-Html | Out-File $dir\badnames.html
}
get_bad_names