get OU Permissions for specific domain - powershell

I found a script that give you OU permissions for the domain the script is run on.
I want to use the same script from a single domain but scan other domains I specify.
The problem I think is with $schemaIDGUID = #{}
When run It's always for the domain the script is running on which is different from the domain I want to run the script on.
Here's the script I modified it to pickup specific domain.
$schemaIDGUID = #{}
$domain = "My specific domain name"
$report = #()
$schemaIDGUID = #{}
$ErrorActionPreference = 'SilentlyContinue'
Get-ADObject -Server $domain -SearchBase (Get-ADRootDSE -Server $domain).schemaNamingContext -LDAPFilter '(schemaIDGUID=*)' -Properties name, schemaIDGUID |
ForEach-Object {$schemaIDGUID.add([System.GUID]$_.schemaIDGUID,$_.name)}
Get-ADObject -SearchBase "CN=Extended-Rights,$((Get-ADRootDSE -Server $domain).configurationNamingContext)" -LDAPFilter '(objectClass=controlAccessRight)' -Properties name, rightsGUID |
ForEach-Object {$schemaIDGUID.add([System.GUID]$_.rightsGUID,$_.name)}
$ErrorActionPreference = 'Continue'
$OUs = #(Get-ADDomain -Server $domain | Select-Object -ExpandProperty DistinguishedName)
$OUs += Get-ADOrganizationalUnit -Server $domain -Filter * | Select-Object -ExpandProperty DistinguishedName
$OUs += Get-ADObject -Server $domain -SearchBase (Get-ADDomain -Server $domain).DistinguishedName -SearchScope OneLevel -LDAPFilter '(objectClass=container)' | Select-Object -ExpandProperty DistinguishedName
ForEach ($OU in $OUs) {
$report += Get-Acl -Path "AD:\$OU" |
Select-Object -ExpandProperty Access |
Select-Object #{name='organizationalUnit';expression={$OU}}, `
#{name='objectTypeName';expression={if ($_.objectType.ToString() -eq '00000000-0000-0000-0000-000000000000') {'All'} Else {$schemaIDGUID.Item($_.objectType)}}}, `
#{name='inheritedObjectTypeName';expression={$schemaIDGUID.Item($_.inheritedObjectType)}}, `
*
}
$report | Export-Csv -Path ".\$domain.OU_Permissions.csv" -NoTypeInformation
#Start-Process ".\$domain.OU_Permissions.csv"
break
$report |
Where-Object {-not $_.IsInherited} |
Select-Object IdentityReference, OrganizationalUnit -Unique |
Sort-Object IdentityReference
$filter = Read-Host "Enter the user or group name to search in OU permissions"
$report |
Where-Object {$_.IdentityReference -like "*$filter*"} |
Select-Object IdentityReference, OrganizationalUnit, IsInherited -Unique |
Sort-Object IdentityReference

Your problem has nothing to do with the $schemaIDGUID variable.
The problem is this line:
$report += Get-Acl -Path "AD:\$OU"
The AD: drive is mapped to ADWS on a DC in your home domain, on module import, so you'll need to explicitly create another drive that maps to the target domain instead:
$domain = "other.domain.tld"
# discover naming context + find a DC to query
$defaultNC = (Get-ADRootDSE -Server $domain).defaultNamingContext
$DC = Get-ADDomainController -Server $domain
# map new ADTemp:\ drive
New-PSDrive -Name ADTemp -PSProvider ActiveDirectory -Root $defaultNC -Server $DC
For the rest of the script, the only thing you need to change is the previously mentioned line, to:
$report += Get-Acl -Path "ADTemp:\$OU"

Related

Export computer name from after .ntSecurityDescriptor output

I have the following code, I'm just trying to export what security groups are attached to each Domain Controller.
I have so far made this, however! I cannot seem to export the computer names along side the Groups in the output! Can someone potentially help! I've been going round in circles for hours
$ou = "OU=Domain Controllers,DC=example,DC=com"
$user = Get-ADComputer -SearchBase $ou -Filter * -properties * | Select ntSecurityDescriptor, Name
$user2 = $user.ntSecurityDescriptor.Access |
select-object -expandproperty IdentityReference |
sort-object -unique
if ($user2-eq "example\user") {
#They Match
Write-Host "Oh Sugar"
$user.ntSecurityDescriptor.Access |
Select-Object -expandproperty IdentityReference |
sort-object -unique
} else {
Write-Host "Phew"
}
Update 20th August. I updated my code to loop around and show the computer name in the output.
$ou = "OU=Domain Controllers,DC=example,DC=com"
$computers = Get-ADComputer -SearchBase $ou -Filter * -properties ntSecurityDescriptor, Name
$code = foreach ($computer in $computers)
{
Get-ADComputer $computer -properties ntSecurityDescriptor
$owner = $computer.ntSecurityDescriptor.Access |
Select-Object -expandproperty IdentityReference |
sort-object -unique
$export = if ($owner-eq "example\user") {
#Problem found
$computer.Name
} else {
}
$export | Out-File 'C:\Temp\output.csv' -Append
}

Matching security group names based on $variable.name

Ok so I'm trying to automate the creation of security groups under a specific OU. The keystone is group membership, so basically If member of group A -> create group B.
So I'm filling a variable with the name attribute of an "All Managers" group. Then I want to loop through those $names and check for the existence of another group using {Name -like 'Reports to $name'}
The looping part is throwing me off, here's what I've got:
import-module activedirectory
$ou = "ou=Stuff, ou=Resources, ou=Groups, ou=Org, dc=domain, dc=net"
$creds = "domain.net\user"
$server = "<domain controller>"
$managers = get-adGroupMember -server $server -Credential $creds -identity "All Managers" | select name
$name = $managers.name
$ReportsTo = Get-adgroup -server $server -credential $creds -searchbase $ou -filter "Name -like 'Reports to *'" | where {$_.name -replace 'Reports to ' -in $name} | select name
$Reports = $reportsto.name
$reports
ForEach ($manager in $managers){
If ($ReportsTo -NotContains $name)
#{$name}
{New-ADGroup -name "Reports to "$name -groupscope Global -path $ou}
}
it's ugly I know, but like i said I'm not sure how to process the loop, they are still new to me.
You may do the following:
$ou = 'ou=Stuff,ou=Resources,ou=Groups,ou=Org,dc=domain,dc=net'
$creds = "domain.net\user"
$server = "<domain controller>"
# Get Manager names only
$managers = Get-ADGroupMember -Server $server -Credential $creds -Identity 'All Managers' |
Select-Object -ExpandProperty Name
# Get Group names that are in the format Reports to Manager Name
$ReportsTo = Get-ADGroup -Server $server -Credential $creds -SearchBase $ou -Filter "Name -like 'Reports to *'" |
where {$_.Name -replace 'Reports to ' -in $managers} |
Select-Object -ExpandProperty Name
# Find manager names that don't have a Reports to group
Compare-Object $managers ($ReportsTo -replace 'Reports to ') -PassThru | Foreach-Object {
# Pipe found manager names into New-ADGroup command's -Name parameter
New-ADGroup -Name "Reports to $_" -GroupScope Global -Path $ou -Server $server -Credential $creds
}
Compare-Object by default only lists differences.

Retrieving Bitlocker Recovery Keys from AD

Fairly new to Powershell, I managed to get the following code to retrieve the Bitlocker key for computers in the domain, however, I have an issue with it:
Clear-Host
$TestOU = "OU=ABC,DC=XYZ,DC=com"
$PCs = Get-ADComputer -Filter * -SearchBase $TestOU
$Results = ForEach ($Computer in $PCs)
{
New-Object PSObject -Property #{
ComputerName = $Computer.Name
RecoveryPassword = Get-ADObject -Filter 'objectclass -eq "msFVE-
RecoveryInformation"' -SearchBase $computer.DistinguishedName -Properties
msFVE-RecoveryPassword,whencreated | sort whencreated -Descending | select
msfve-recoverypassword
}
}
$Results
My output for each password begins with {a{msfve-recoverypassword= and I'm not sure how to remove this.
The following code gives useful output for human consumption in the shell, but may also be used in a script:
$computer = Get-ADComputer $computerName
Get-ADObject -Filter 'objectClass -eq "msFVE-RecoveryInformation"' -SearchBase $computer.DistinguishedName -Properties whenCreated, msFVE-RecoveryPassword | `
Sort whenCreated -Descending | Select whenCreated, msFVE-RecoveryPassword

Get UPN from Get-ADGroupMember

I have a task to get userPrincipalName attribute from users who are in several groups in our multiple-domain AD forest.
The problem is that I can't use Select-Object to get a user's UPN from Get-ADGroupMember because this cmdlet only returns a limited number of properties (samaccountname, name, SID and DN), and UPN isn't one of them.
I wrote this code (get "name" and than search UPN by "name"):
$ScriptPath = Split-Path $MyInvocation.MyCommand.Path
$LocalSite = (Get-ADDomainController -Discover).Site
$NewTargetGC = Get-ADDomainController -Discover -Service 6 -SiteName
$LocalSite
IF (!$NewTargetGC)
{ $NewTargetGC = Get-ADDomainController -Discover -Service 6 -NextClosestSite }
$NewTargetGCHostName = $NewTargetGC.HostName
$LocalGC = “$NewTargetGCHostName” + “:3268”
$domains = (Get-ADForest).domains
$MembersOfSFDC_Groups = foreach ($domain in $domains) {
$Group = Get-ADGroup -Filter { Name -like "*groupname*" } -Server $Domain
$Group | Get-ADGroupMember -Server $domain | Select #{
Name="Domain";Expression={$Domain}},#{
Name="Group";Expression={$Group.Name}}, name}
$DisplayNames = $MembersOfSFDC_Groups.name
$DisplayNames |Out-file (Join-Path $ScriptPath 'DisplayNames.txt')
Get-content (Join-Path $ScriptPath 'DisplayNames.txt') |
$displaynames | ForEach-Object {
Get-ADUser -Server $LocalGC -Filter {Name -eq $_} |
Select-Object -Property userPrincipalName} |
Out-File (Join-Path $ScriptPath 'upnOfSDFC_AD_GroupsMembers.txt')
But next problem is that this code is running about 30 min (Measure-Command cmdlet). We have a huge number of users across multiple domains.
My question is how to improve my code to get user's UPN more faster?
I know about System.DirectoryServices.DirectorySearcher, but don't know how to implementing this method with my txt-file (list of "names").
Any help will be much appreciated.
You can actually get it from one line of code. Simples... :)
Get-ADGroupMember -Identity "group name" |%{get-aduser $_.SamAccountName | select userPrincipalName } > c:\scripts\upnofADgroup.txt
Fastest approach is probably avoiding Get-ADGroupMember altogether, and just search for the group, and then search for objects that are members of that group:
$Group = Get-ADGroup -Filter { Name -like "*groupname*" } -Server $Domain
$Members = Get-ADObject -LDAPFilter "(memberOf=$($Group.DistinguishedName))" -Properties UserPrincipalName
$Members |Select-Object UserPrincipalName |Out-File (Join-Path $ScriptPath 'upnOfSDFC_AD_GroupsMembers.txt')
Now you're down to 2 queries, rather than 2 + N (where N is the number of members)
Ok, guys, I'v got it:
function Get-DomainFromDN ($param)
{
$dn1 = $param -split "," | ? {$_ -like "DC=*"}
$dn2 = $dn1 -join "." -replace ("DC=", "")
$script:test = $dn2
return $dn2
}
foreach ($Group in $Groups) {
$Members = Get-ADObject -LDAPFilter "(&(objectCategory=user)(memberOf=$($Group.DistinguishedName)))" -Properties UserPrincipalName -Server (Get-DomainFromDN ($group.DistinguishedName))
$UPN_Of_SFDC_Groups += $Members |Select-Object UserPrincipalName }
$UPN_Of_SFDC_Groups | Out-file (Join-Path $ScriptPath 'upnOfSDFC_AD_GroupsMembers.txt')

Powershell ALL AD Users and their Group Memberships

Looking to write a powershell script that will pull ALL AD users, their group memberships and the groups Description Field.
I have been using two scripts to accomplish this, and just manually manipulating them in excel. Any attempt to combine them has been met with error.
Import-module activedirectory
$ou ="DC=blah,DC=blah"
Get-ADGroup -Filter * -SearchBase $OU | select -expandproperty name | % {
$group= "$_"
$result += Get-ADGroupMember -identity "$_" | select #{n="Group";e={$group}},name
}
$result | export-csv 'c:\users\membership.csv' -notypeinformation
And:
Import-Module ActiveDirectory
$Groups = ForEach ($G in (Get-ADGroup -Filter * ))
{
$UN = Get-ADGroup $G -Properties Description | select name, description
New-Object PSObject -Property #{
Desc=$UN.description
Name=$UN.name
}
}
$Groups | Export-CSV C:\users\GroupDesc.csv -notypeinformation
I hope i've got this right, this will pull all users from AD and get the groups each one is a member of (including the groups description). After everything is done it puts the info into a csv.
Import-Module ActiveDirectory
$OU = "DC=blah,DC=blah"
#$allUsers = Get-ADUser -LDAPFilter "(&(objectCategory=person)(objectClass=user)(!userAccountControl:1.2.840.113556.1.4.803:=2))" # all users that are enabled
#$allUsers = Get-ADUser -Filter * # all users
$allUsers = Get-ADUser -Filter * -SearchBase $OU
$results = #()
foreach($user in $allUsers)
{
$userGroups = Get-ADPrincipalGroupMembership -Identity $user
foreach($group in $userGroups)
{
$adGroup = Get-ADGroup -Identity $group -Properties Description
$results += $adGroup | Select-Object -Property #{name='User';expression={$user.sAMAccountName}},Name,Description
}
}
$results | Export-Csv -Path 'C:\Membership.csv' -NoTypeInformation -Encoding Unicode