Create CSV file of deleted users from active directory - powershell

Got the following code, I can created the CSV file of users, but would like it to be only populated by the users that will get deleted from the loop above it. Just not saw how to integrate both together.
Basically, its pulls all users that will get deleted that are 90 days + old, then the users information gets put in to a CSV.
$OU='OU=Users,OU=Test,DC=corporate,DC=domain,DC=com'
$LISTOFACCOUNTS=Get-ADUser -Property lastlogondate -SearchBase $OU -Filter {lastLogonDate -lt $NumberDays}
$LISTOFACCOUNTS | DISABLE-ADACCOUNT -WhatIf
$LISTOFPOTENTIALDELETES=Get-ADUser -SearchBase $OU -Property Lastlogondate -Filter` {lastlogondate -lt $DeleteDate}
FOREACH ($USER in $LISTOFPOTENTIALDELETES) {
IF (($USER.Notes -notlike '*'+$OVERRIDE+'*') -and ($USER.Description -notlike` '*'+$OnLeave+'*'))
{
WRITE-HOST $USER.SamAccountName 'Deleted'
REMOVE-ADOBJECT $USER.SamAccountName -whatif
}
ELSEIF ($USER.Notes -like '*'+$OVERRIDE+'*')
{
WRITE-HOST $USER.SamAccountName 'Not removed due to Administrative Override'
}
ELSE
{
WRITE-HOST $USER.SamAccountName 'Not removed - Presently on Leave'
}
}
$memberOf = #{n='MemberOf';e={ ($_.MemberOf -replace '^CN=([^,]+).+$','$1') -join ';' }}
$LastLogonDays = #{N='Last Logon Days'; E={$($(Get-Date) - ` $([DateTime]::FromFileTime($_.LastLogon))).Days}}
$LastLogon = #{N='LastLogon'; E={[DateTime]::FromFileTime($_.LastLogon)}}
$Mail = #{ Name = 'mail'; Expression = { $_.mail -join ';'; }; }
$Description = #{N='Description'; E={$_.description -join ';'; }; }
Get-ADUser -Filter * -SearchBase $OU -Properties * | Select Enabled, SAMAccountName, ` CanonicalName, Displayname,Givenname, Surname, Department, `
ProfilePath, HomeDrive, $Description, $LastLogonDays, $LastLogon, $mail, $memberOf |
Export-CSV "E:\Temp\_DisabledUserList.csv"
Cheers in advance

Build a list with the user objects before they're deleted:
$deletedUsers = #()
foreach ($USER in $LISTOFPOTENTIALDELETES) {
if ($USER.Notes -notlike ...) {
Write-Host $USER.SamAccountName 'Deleted'
$deletedUsers += $USER
Remove-ADObject $USER.SamAccountName -WhatIf
} else {
...
}
}
and export that list to a CSV:
$deletedUsers | select SamAccountName, ... | Export-Csv 'C:\Temp\deleted.csv'
Side note: I'd recommend using Remove-ADUser instead of Remove-ADObject for removing AD users.

Related

Getting both computer and user objects from inside security group via powershell

I can get the user accounts in the group with the following script. But I want to get both computer object and user object in some groups. how can I do it?
Import-Module ActiveDirectory
$groups = Get-ADGroup -Filter "Name -like 'TST*'"
ForEach ($Group in $Groups) {
Get-ADGroupMember -Identity $group |
Get-ADUser -Properties samaccountname,mail,AccountExpires,manager,employeeid,employeetype |
Select-Object samaccountname,mail,employeeid,employeetype,#{l="expiration_date";e={ accountExpiresToString($_.AccountExpires)}},#{n=”Manager Name”;e={(Get-ADuser -identity $_.Manager -properties displayname).DisplayName}} |
Export-CSV -Path "C:tmp\$($group.Name).csv" -NoTypeInformation
}
Just test for the objectclass and deal with accordingly. Use a custom object to construct the output.
Import-Module ActiveDirectory
$groups = Get-ADGroup -Filter "Name -like 'TST*'"
$groups | ForEach-Object {
$Results = Get-ADGroupMember -Identity $_ | ForEach-Object {
#
# For each objectclass you must output the same properties else
# the custom PS object will not construct across object types
# I find this the best way to make it obvious what your code is doing:
#
If ($_.objectclass -eq 'user') {
$ObjDetails = Get-ADUser -Identity $_ -Properties mail,AccountExpires,manager,employeeid,employeetype
$Mail = $ObjDetails.mail
$EmployeeID = $ObjDetails.employeeid
$EmployeeType = $ObjDetails.employeetype
# Unless you're SURE all these fields are populated correctly use Try...Catch or test for the field before assigning
Try {
$ManagerName = (Get-ADuser -identity $ObjDetails.Manager -properties displayname -ErrorAction Stop).DisplayName
}
Catch {
$ManagerName = 'Not found'
}
# Not in a User object, but you must define empty fields
$DNSHostName = ''
}
If ($_.objectclass -eq 'computer') {
$ObjDetails = Get-ADComputer -Identity $_ -Properties DNSHostName
# These fields are not in a Computer object but you must define them
$Mail = ''
$EmployeeID = ''
$EmployeeType = ''
$ManagerName = ''
# This field unique to computer object
$DNSHostName = $ObjDetails.DNSHostName
}
[pscustomobject]#{
SamAccountName = $ObjDetails.SamAccountName
Mail = $Mail
EmployeeID = $EmployeeID
EmployeeType = $EmployeeType
ManagerName = $ManagerName
DNSHostName = $DNSHostName
}
}
# You can then display/export results object
$Results # | Export-CSV -Path "C:\tmp\$($group.Name).csv" -NoTypeInformation
}

Using a .txt file to find ManagedBy and ManagedBy Email within an AD Group

I'm having issues trying to have my script read and apply the AD groups with my script. Right now, it's just posting what's in my script, but I would like to have the script read what's in my .txt file and use it with the rest of my script.
$filePath = "C:\Users\UserName\Downloads\ADGroupList.txt"
Get-Content -Path $filePath
Get-ADGroup -filter {Name -like "$filePath" } -Properties managedBy |
ForEach-Object {
$managedBy = $_.managedBy;
if ($managedBy -ne $null)
{
$manager = (get-aduser -Identity $managedBy -Properties emailAddress);
$managerName = $manager.Name;
$managerEmail = $manager.emailAddress;
}
else
{
$managerName = 'N/A';
$managerEmail = 'N/A';
}
Write-Output $_; } |
Select-Object #{n='Group Name';e={$_.Name}}, #{n='Managed By Name';e={$managerName}}, #{n='Managed By Email';e={$managerEmail}}
Export-Csv -Path "C:\Users\UserName\Documents\ADGroupManagerList.csv"
The easiest way is to loop over the group names you have in the ADGroupList.txt file (assuming this is a list of group names, each on a separate line)
$filePath = "C:\Users\UserName\Downloads\ADGroupList.txt"
# just loop over the group names you have in the text file and capture the output
$result = Get-Content -Path $filePath | ForEach-Object {
$group = Get-ADGroup -Filter "Name -like '$_'" -Properties managedBy
# create an object pre filled in when no manager was found
$obj = [PsCustomObject]#{
'Group Name' = $group.Name
'Managed By Name' = 'N/A'
'Managed By Email' = 'N/A'
}
# test if the ManagedBy is populated
if (-not [string]::IsNullOrWhiteSpace($group.ManagedBy)) {
# try to use the DN in property ManagedBy to find the manager
try {
$manager = Get-ADUser -Identity $group.ManagedBy -Properties EmailAddress -ErrorAction Stop
$obj.'Managed By Name' = $manager.Name
$obj.'Managed By Email' = $manager.EmailAddress
}
catch {
Write-Warning "No user found for '$($group.ManagedBy)'.. Please check AD."
}
}
# output the object so it gets collected in variable $result
$obj
}
# write the file
$result | Export-Csv -Path "C:\Users\UserName\Documents\ADGroupManagerList.csv" -NoTypeInformation
For workaround you can use this powershell script to get the mangedBy of groups.
Get-ADGroup -filter * -Properties managedBy |
ForEach-Object {
$managedBy = $_.managedBy;
if ($managedBy -ne $null)
{
$manager = (get-aduser -Identity $managedBy -Properties emailAddress);
$managerName = $manager.Name;
$managerEmail = $manager.emailAddress;
}
else
{
$managerName = 'N/A';
$managerEmail = 'N/A';
}
Write-Output $_; } |
Select-Object #{n='Group Name';e={$_.Name}}, #{n='Managed By Name';e={$managerName}}, #{n='Managed By Email';e={$managerEmail}}

If user belongs to this group, show this, if not, show this

I am a novice to powershell and starting to learn the syntax and what logic is needed, but I have given this a good go.
I need to pop in a conditional field that does the below
If users are a member of the "Domain Admins" group, then show "Administrator"
If users are a member of the "ReadOnlyAccess" group, then show "Read Only"
But my script doesn't quite do this and I wandered how my script could be changed to get what I need it to do.
This is my script below:
Import-Module ActiveDirectory
$OUPath = "OU=1_Users,DC=DGDomain,DC=Local"
$filepath = "C:\temp\users.csv"
$readonlygroup = "ReadOnlyAccess"
$readonlygroupmembers = Get-ADGroupMember -Identity $readonlygroup | Get-ADUser -Properties SamAccountName | Select SamAccountName
$admingroup = "Domain Admins"
$admingroupmembers = Get-ADGroupMember -Identity $admingroup | Get-ADUser -Properties SamAccountName | Select SamAccountName
$users = Get-ADUser -Filter * -Properties * -SearchBase $OUPath |
Where-Object { $_.Enabled -eq $true } |
Select SamAccountName
Get-ADUser -Filter * -Properties * -SearchBase $OUPath |
Where-Object { $_.Enabled -eq $true } |
Select SamAccountName,
DisplayName,
#{Label = "Access Level"
Expression = {
foreach ($user in $users) {
if ($readonlygroupmembers -contains $users)
{ "Read Only" }
else {
if ($admingroupmembers -contains $users)
{ "Administrator" }
else
{ "None" }
}
} } } |
Export-csv $filepath -NoTypeInformation
This should do the trick:
$OUPath = "OU=1_Users,DC=DGDomain,DC=Local"
$filepath = "C:\temp\users.csv"
$readonlygroup = "ReadOnlyAccess"
$readonlygroupmembers = (Get-ADGroupMember -Identity $readonlygroup | Get-ADUser -Properties SamAccountName).SamAccountName
$admingroup = "Domain Admins"
$admingroupmembers = (Get-ADGroupMember -Identity $admingroup | Get-ADUser -Properties SamAccountName).SamAccountName
$users = Get-ADUser -Filter { Enabled -eq $true } -SearchBase $OUPath -Properties DisplayName
foreach ($user in $users) {
if ($user.SamAccountName -in $admingroupmembers) { $groupMembership = 'DomainAdmin'}
elseif ($user.SamAccountName -in $readonlygroupmembers) { $groupMembership = 'ReadOnly' }
else {$groupMembership = 'None'}
[PSCustomObject]#{
DisplayName = $user.DisplayName
SamAccountName = $user.SamAccountName
AccessLevel = $groupMembership
}
}
Export-csv $filepath -NoTypeInformation

Powershell script for getting AD Group Membership for usernames

I want to write script for getting AD Group Membership that is beginning with SSL_VPN for usernames listed in a CSV.
I have tried so far :
Import-Csv C:\Users.csv |
ForEach-Object -pv user { Get-AdUser -filter "displayname -eq '$($_.username)'"} |
Get-ADprincipalGroupMembership |
Select-Object #{ n = 'samaccountname'; e = { $user.samaccountname } }, name |
Export-csv -path C:\UserPermiss.csv -NoTypeInformation
Getting users by their DisplayName property is not the safest thing to do. It would be so much better if your CSV file has other, more unique properties to go by, like SamAccountName, UserPrincipalName, DistinguishedName or EmailAddress..
Anyway, in your loop, you should check if a user with that name can be found and only if so, get the group membership.
Import-Csv 'C:\Users.csv' | ForEach-Object {
$user = Get-ADUser -Filter "DisplayName -eq '$($_.username)'" -Properties DisplayName
if ($user) {
Get-ADprincipalGroupMembership -Identity $user.DistinguishedName |
Where-Object { $_.name -like 'SSL_VPN*' } |
Select-Object #{ Name = 'SamAccountName'; Expression = { $user.SamAccountName } },
#{ Name = 'Group'; Expression = { $_.name }}
}
else {
Write-Warning "User '$($_.username)' not found"
# if you want this message to also appear in your output CSV, do something like this:
[PsCustomObject]#{
'SamAccountName' = "User '$($_.username)' not found"
'Group' = ''
}
}
} | Export-Csv -Path 'C:\UserPermiss.csv' -NoTypeInformation
If you want to see a warning message when the user is not a member of the SSL_VPN group, you can do:
Import-Csv 'C:\Users.csv' | ForEach-Object {
$user = Get-ADUser -Filter "DisplayName -eq '$($_.username)'" -Properties DisplayName
if ($user) {
$group = Get-ADprincipalGroupMembership -Identity $user.DistinguishedName |
Where-Object { $_.name -like 'SSL_VPN*' }
if ($group) {
[PsCustomObject]#{
'SamAccountName' = $user.SamAccountName
'Group' = $group.name
}
}
else {
Write-Warning "User '$($_.username)' is not a member of ssl_vpn group"
}
}
else {
Write-Warning "User '$($_.username)' not found"
}
} | Export-Csv -Path 'C:\UserPermiss.csv' -NoTypeInformation
You can use something like this(frist line of csv must be samaccountname):
$users=Import-Csv D:\adusers.CSV
foreach($user in $users){
$groupname=Get-ADPrincipalGroupMembership -Identity $user.samaccountname |where {$_.name -like "SSL_VPN*"}|select -ExpandProperty name
if($groupname -ne $null){
foreach($group in $groupname){
[string]$data=($user|select -ExpandProperty samaccountname)+';'+$group
$data|Out-File -FilePath d:\stack.csv -Encoding utf8 -Append
}
}
}

Remove groups from Member of tab from user properties

I am new to powershell Below scripts i have which remove all groups from the user member of tab except "Domain users" this works fine many time without any issues
Removing Groups from User
$list = Import-Csv c:\user\DN.csv
foreach ($entry in $list)
$UserDN = $entry.DistinguishedName
Get-ADGroup -LDAPFilter "(member=$UserDN)" | foreach-object {
if ($_.name -ne "Domain Users") {remove-adgroupmember -identity $_.name -member $UserDN -Confirm:$False}
But the problem is when if this script is not able to remove any group from user member of tab it throws an error below but it doesn't shows from which user id it was unable to remove the membership as the user distinguished name is imported from a CSV file.
Remove-ADGroupMember : The specified account name is not a member of the group
At C:\User\removegroups.ps1:35 char:115
+ Get-ADGroup -LDAPFilter "(member=$UserDN)" | foreach-object {if ($_.name -ne "Domain Users") {remove-adgroupmember <<
<< -identity $_.name -member $UserDN -Confirm:$False}
+ CategoryInfo : NotSpecified: (xyz:ADGroup) [Remove-ADGroupMember], ADException
+ FullyQualifiedErrorId : The specified account name is not a member of the group,Microsoft.ActiveDirectory.Management.Commands.RemoveADGroupMember
$list = Import-Csv c:\user\DN.csv
foreach ($entry in $list)
$UserDN = $entry.DistinguishedName
Get-ADGroup -LDAPFilter "(member=$UserDN)" | foreach-object {
if ($_.name -ne "Domain Users") {
try {
remove-adgroupmember -identity $_.name -member $UserDN -Confirm:$False} }
catch [ADexcption] {
write-output "Error Deleting User:" $_.name
}
}
Import-Csv DN.csv | foreach {
$user = Get-ADUser $_.username
$UserDN = $user.DistinguishedName
Get-ADGroup -LDAPFilter "(member=$UserDN)" | foreach-object {
if ($_.name -ne "Domain Users") {
try {
remove-adgroupmember -identity $_.name -member $UserDN -Confirm:$False
}
catch [ADexcption] {
write-output "Error Deleting User:" $_.name
}
}
}}