Variables in ADUsers2CSV script - powershell

My main goal is to export some info about users from Active Directory to CSV file.
But in my AD, there is also bunch of some service accounts that I don't want to export and I want to use only specific OUs.
So I created CSV file with "list" of these OUs and filenames of exported CSV, looks like:
oubase,oucity,filename
OU=_SubCompany1,OU=_City1,filename1.csv
OU=_SubCompany1,OU=_City2,filename2.csv
OU=_SubCompany3,OU=_City1,filename3.csv
And my PS script:
Import-Module ActiveDirectory
$adserver = "ad1.domain.com"
$filter = "'(& (msExchMailboxGuid=*) (!sAMAccountName=*_*))'"
$selection = "personalTitle, msDS-PhoneticFirstName, msDS-PhoneticLastName, msDS-PhoneticDepartment, Title, mobile, telephoneNumber, facsimileTelephoneNumber, SamAccountName"
$targetpath = "C:\Scripts\ADUsers\export\"
$exportfiles = "C:\Scripts\ADUsers\export\export_files.csv"
Import-Csv -Path $exportfiles | ForEach-Object {
$oubase = $_.'oubase'
$oucity = $_.'oucity'
$filename = $_.'filename'
$fullpath = $targetpath + $filename
$fullbase = "'OU=Users," + $oucity + "," + $oubase + ",DC=domain,DC=com'"
#$fullbase = 'OU=Users,OU=_City2,OU=_SubCompany1,DC=domain,DC=com'
Get-ADUser -Server $adserver -LDAPFilter $filter -Properties * -SearchBase $fullbase |
select $selection |
Export-Csv -Encoding Unicode $fullpath
But the script isn't working. There is some problem with variables in the Get-ADUser command.
When I type in directly all the values, everything is working:
Get-ADUser -Server ad1.domain.com -LDAPFilter '(& (msExchMailboxGuid=*) (!sAMAccountName=*_*))' -Properties * -SearchBase 'OU=Users,OU=_City2,OU=_SubCompany1,DC=domain,DC=com' |
select personalTitle, msDS-PhoneticFirstName, msDS-PhoneticLastName, msDS-PhoneticDepartment, Title, mobile, telephoneNumber, facsimileTelephoneNumber, SamAccountName |
Export-Csv -Encoding Unicode C:\Scripts\ADUsers\export\filename2.csv
When I try to display the content of variables, it seems OK, no extra whitespaces or commas etc.
I think variables $filter and $fullbase are problematic.
When I try it like with $filter variable, command won't return any error and it creates empty CSVs:
Get-ADUser -Server $adserver -LDAPFilter $filter -Properties * -SearchBase 'OU=Users,OU=_City2,OU=_SubCompany1,DC=domain,DC=com' |
select personalTitle, msDS-PhoneticFirstName, msDS-PhoneticLastName, msDS-PhoneticDepartment, Title, mobile, telephoneNumber, facsimileTelephoneNumber, SamAccountName |
Export-Csv -Encoding Unicode C:\Scripts\ADUsers\export\filename2.csv
When I try it with $fullbase variable, command returns this error.
Get-ADUser -Server $adserver -LDAPFilter '(& (msExchMailboxGuid=*) (!sAMAccountName=*_*))' -Properties * -SearchBase $fullbase |
select personalTitle, msDS-PhoneticFirstName, msDS-PhoneticLastName, msDS-PhoneticDepartment, Title, mobile, telephoneNumber, facsimileTelephoneNumber, SamAccountName |
Export-Csv -Encoding Unicode C:\Scripts\ADUsers\export\filename2.csv
Get-ADUser : The supplied distinguishedName must belong to one of the following
partition(s): 'DC=domain,DC=com , CN=Configuration,DC=domain,DC=com ,
CN=Schema,CN=Configuration,DC=domain,DC=com , DC=DomainDnsZones,DC=domain,DC=com ,
DC=ForestDnsZones,DC=domain,DC=com'.
At C:\Scripts\ADUsers\export\ad-users_export-csv.ps1:21 char:1
+ Get-ADUser -Server $adserver -LDAPFilter '(& (msExchMailboxGuid=*) (!sAMAccountN ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Get-ADUser], ArgumentException
+ FullyQualifiedErrorId : ActiveDirectoryCmdlet:System.ArgumentException,Microsoft.ActiveDirectory.Management.Commands.GetADUser
Do you have any ideas what am I doing wrong?

Related

Powershell variable issue Get-Content and Get-ADGroup

I'm trying to figure out the reason why I can run the script using variable $groups with Get-Content but it wont work if variable $groups goes with Get-ADGroup list I did below...
Block that works:
$groups = Get-Content C:\groups.csv
$results = #()
$file = "C:\Usuarios_Grupos_Darwin_AD.csv"
foreach($Group in $Groups) {
$results +=Get-ADGroupMember -Id $Group -Recursive | %{Get-ADUser -Identity $_.SamAccountName -Properties Enabled,Name} | Select #{Expression={$Group};Label=”Group Name”},SamAccountName,Name,Enabled
}
$results | export-csv -notypeinformation -Delimiter ";" -path $file
Block that's not working:
(only the first line has been changed)
$groups = Get-ADGroup -Filter {Name -like '*Darwin*'} -Properties * | select -property Name
$results = #()
$file = "C:\Usuarios_Grupos_Darwin_AD.csv"
foreach($Group in $Groups) {
$results +=Get-ADGroupMember -Id $Group -Recursive | %{Get-ADUser -Identity $_.SamAccountName -Properties Enabled,Name} | Select #{Expression={$Group};Label=”Group Name”},SamAccountName,Name,Enabled
}
$results | export-csv -notypeinformation -Delimiter ";" -path $file
Here is the error:
Get-ADGroupMember : Cannot bind parameter 'Identity'. Cannot create object of type "Microsoft.ActiveDirectory.Management.ADGroup". The adapter cannot set the value of property
"Name".
At line:11 char:34
+ $results +=Get-ADGroupMember -Id $Group -Recursive | %{Get-ADUser -Id ...
+ ~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Get-ADGroupMember], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.ActiveDirectory.Management.Commands.GetADGroupMember
I'm trying to embed the output list all in one script without having to generate csv with another script.
Thanks in advance !!
A few notes about your code:
the -Filter parameter should be a string, not a scriptblock
using $results += is very costly because the entire array needs to be rebuilt in memory on each addition
Get-ADGroupMember can return also computer and (when not used with -Recursive) also group objects, not just users, so you cannot pipe directly to Get-ADUser
never use -Properties * if all you want is one single property
Try this:
# Get-ADGroup already returns objects with these properties:
# DistinguishedName, GroupCategory, GroupScope, Name, ObjectClass, ObjectGUID, SamAccountName, SID
$groups = Get-ADGroup -Filter "Name -like '*Darwin*'"
$file = "C:\Usuarios_Grupos_Darwin_AD.csv"
# let PowerShell collect the objects for you instead of using +=
$results = foreach($Group in $Groups) {
# Get-ADGroupMember can return objects of type users and computers (also groups when used without -Recursive)
# so filter the result to get only user objects
$Group | Get-ADGroupMember -Recursive | Where-Object { $_.objectClass -eq 'user' } | ForEach-Object {
$_ | Get-ADUser | Select #{Name = 'Group Name'; Expression={$Group.Name}}, SamAccountName, Name, Enabled
}
}
$results | Export-Csv -Path $file -NoTypeInformation -Delimiter ";"

Update Active Directory (On-Prem) User Attribute via Powershell

I tried to not bug you all, but I'm at a loss. I'll preface with, I'm still relatively new to PS, so my apologies for any ignorance.
Need: To update users' attribute (extensionAttribute1 to be precise) to "First.Last" (or rather, "givenName.Surname") for all users in AD.
Problem: When I try to run the Powershell below (I was trying 2 different methods for update, hence the commented out portion), I get the outputs below.
Import-Module ActiveDirectory
Get-ADUser -Filter * -SearchBase 'ou=Users,ou=Test,dc=Sample,dc=Com' |
Select SamAccountName |
Export-Csv -Path 'c:\Scripts\AllUsersSamaccountname.CSV' -NoTypeInformation
$file="c:\Scripts\AllUsersSamaccountname.CSV"
(gc $file | select -Skip 1) | sc $file
$Users = Import-Csv -Path "c:\Scripts\AllUsersSamaccountname.CSV" -Header "AccountName"
foreach($User in $Users){
$ADUser = Get-ADUser -Identity $User.AccountName -Properties extensionAttribute1
$ADUserG = Get-ADUser -Identity $User.AccountName -Properties givenName
$ADUserS = Get-ADUser -Identity $User.AccountName -Properties Surname
#$ADUser.extensionAttribute1 = [Array]$ADUserG + '.' + $ADUserS
Set-ADUser -Instance $ADUser -replace #{extensionAttribute1=([Array]$ADUserG + '.' + $ADUserS)}
}
Get-ADUser -Filter * -SearchBase 'ou=Users,ou=Test,dc=George,dc=Com' |
Select extensionAttribute1 |
Export-Csv -Path 'c:\Scripts\new-AllUserinfo6.CSV' -NoTypeInformation
Output for Set-ADUser -Instance $ADUser -replace #{extensionAttribute1=([Array]$ADUserG + '.' + $ADUserS)
Set-ADUser : Cannot validate argument on parameter 'Replace'. All values in the argument collection should be of
the same type.
At line:17 char:44
+ ... er -replace #{extensionAttribute1=([Array]$ADUserG + '.' + $ADUserS)} ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Set-ADUser], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.ActiveDirectory.Management.Commands.Set
ADUser
Output for #$ADUser.extensionAttribute1 = [Array]$ADUserG + '.' + $ADUserS
Exception setting "extensionAttribute1": "The adapter cannot set the value of property "extensionAttribute1"."
At line:16 char:6
+ $ADUser.extensionAttribute1 = [Array]$ADUserG + '.' + $ADUserS
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], SetValueInvocationException
+ FullyQualifiedErrorId : CatchFromBaseAdapterSetValue
Any help or guidance would be greatly appreciated...
You are casting the givenName to an array. More than likely that's causing the whole expression to return an array, which isn't acceptable for extensionAttribute1.
I didn't test this but rewriting the loop to something like below should work:
foreach($User in $Users)
{
$ADUser = Get-ADUser -Identity $User.AccountName -Properties extensionAttribute1
$ADUserG = Get-ADUser -Identity $User.AccountName -Properties givenName
$ADUserS = Get-ADUser -Identity $User.AccountName -Properties Surname
$extensionAttribute1 = ($ADUserG.givenName + '.' + $ADUserS.Surname)
$ADUser.extensionAttribute1 = $extensionAttribute1
Set-ADUser -Instance $ADUser
}
Note: that you must reference the properties for givenName & Surname in order to concatenate them as strings. Otherwise you are trying to add 2 user objects together and will get an error.
Additional Info:
If this were me I would write this to be more concise. However, considering you are relatively new to PowerShell, I'd just make one recommendation. In the loop you don't need to get the user account multiple times, something like the below should work and be a little faster.
Import-Module ActiveDirectory
Get-ADUser -Filter * -SearchBase 'ou=Users,ou=Test,dc=Sample,dc=Com' |
Select-Object SamAccountName |
Export-Csv -Path 'c:\Scripts\AllUsersSamaccountname.CSV' -NoTypeInformation
$file="c:\Scripts\AllUsersSamaccountname.CSV"
(Get-Content $file | Select-Object -Skip 1) | Set-Content $file
$Users = (Import-Csv -Path "c:\Scripts\AllUsersSamaccountname.CSV" -Header "AccountName")
foreach($User in $Users)
{
$ADUser = Get-ADUser -Identity $User.AccountName -Properties 'extensionAttribute1','givenName','Surname'
$extensionAttribute1 = ($ADUser.givenName + '.' + $ADUser.Surname)
$ADUser.extensionAttribute1 = $extensionAttribute1
Set-ADUser -Instance $ADUser
}
Get-ADUser -Filter * -SearchBase 'ou=Users,ou=Test,dc=George,dc=Com' |
Select-Object extensionAttribute1 |
Export-Csv -Path 'c:\Scripts\new-AllUserinfo6.CSV' -NoTypeInformation

Getting AD groups and their users

I've been trying to get a list of all the groups in our AD environment (with the description) and their members and output it to a CSV file. Ideally the users would be shown under their group. The script I've been trying to use is:
Import-Module ActiveDirectory
Get-ADGroup -Filter * -Properties Description |
Select-Object Name, Description |
ForEach-Object {
Get-ADGroupMember -Identity $_.DistinguishedName -Recursive |
Get-ADObject -Properties SamAccountname, Title, Department |
Select-Object Name, SamAccountName, Title, Department, DistinguishedName, ObjectClass
} | Export-Csv -Path c:\temp\ADGrab.csv -NoTypeInformation
The error I keep getting is as follows:
Get-ADGroupMember : Cannot validate argument on parameter 'Identity'. The argument
is null or empty. Supply an argument that is not null or empty and then try the
command again.
At C:\Users\j_kennedy_ta\AppData\Local\Temp\9\2898ceb2-a6cf-4fbf-9341-e651dad2145d.ps1:4 char:28
+ Get-ADGroupMember -Identity <<<< $_.distinguishedname -Recursive |
+ CategoryInfo : InvalidData: (:) [Get-ADGroupMember], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.ActiveDirectory.Management.Commands.GetADGroupMember
Without the nasty Select-Object and with group information in the CSV file:
Import-Module ActiveDirectory
Get-ADGroup -Filter * -Properties Description |
ForEach-Object {
# Store for later use
$groupName = $_.Name
$groupDescription = $_.Description
Get-ADGroupMember -Identity $_.DistinguishedName -Recursive |
Get-ADObject -Properties SamAccountname, Title, Department |
Select-Object Name, SamAccountName, Title, Department, DistinguishedName, ObjectClass, ` # Mind the gap
# Calculated properties with group information
#{ name = "GroupName"; expression = $groupName }, `
#{ name = "GroupDescription"; expression = $groupDescription }
} | Export-Csv -Path c:\temp\ADGrab.csv -NoTypeInformation

Filter Managedby Powershell

Below are my current attempts to pull AD groups whose managedby equal names like "ML...". I keep getting errors so I wanted to know why I am unable to filter managedby with "-like" when I can filter managedby "-eq $..." variables. I tried making a variable $name = "ML*" so that I can perform {managedby -eq $name} but still had no luck.
I mostly get error like:
Operator(s): The following: ''Eq', 'Ne'' are the only operator(s) suppor
ted for searching on extended attribute: 'ManagedBy'.
and so forth because "-eq" is only accepted for some filters I have done. When I use -eq I get these errors:
Import-Module : The following error occurred while loading the extended type dat
a file:
Microsoft.PowerShell, C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules\ActiveD
irectory\ActiveDirectory.Types.ps1xml : File skipped because it was already pres
ent from "Microsoft.PowerShell".
Microsoft.PowerShell, C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules\ActiveD
irectory\ActiveDirectory.Types.ps1xml : File skipped because it was already pres
ent from "Microsoft.PowerShell".
At J:\\ManagedbyEqualsML.ps1:1 char:14
+ Import-Module <<<< ActiveDirectory
+ CategoryInfo : InvalidOperation: (:) [Import-Module], RuntimeExc
eption
+ FullyQualifiedErrorId : FormatXmlUpateException,Microsoft.PowerShell.Comm
ands.ImportModuleCommand
The term 'Get-adgroup' is not recognized as the name of a cmdlet, function, scri
pt file, or operable program. Check the spelling of the name, or if a path was i
ncluded, verify that the path is correct and try again.
At J:\\ManagedbyEqualsML.ps1:53 char:27
+ $MLgroupAll = Get-adgroup <<<< -Properties managedby, enabled, name -filter
{managedby -eq $name}
+ CategoryInfo : ObjectNotFound: (Get-adgroup:String) [], CommandN
otFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
Here are my codes where I attempted to find Owners that have the name ML*
Import-Module ActiveDirectory
$name = "ML*"
#Attempt 1
$MLgroups = Get-adgroup -Properties managedby, enabled, name -filter * | Select name, managedby
foreach ($group in $MLgroups){
if ($group.managedby -like "ML*"){
write-host $group.name + $group.managedby}
}
#Attempt 2
$Mgroups = get-adgroup -Properties name, managedby -filter *
foreach ($groups in $Mgroups){
# here get the group name and use the "managedBy attribute to retrieve the user object
# grou naem
$gname = $_.Name
$manager=Get-AdUser $_.ManagedBy
$MangerName = $manager.DisplayName
if ($managerName -like "ML*"){
write-host $gname + $managerName}
}
#Attempt 3
$exportlist = "C:\Temp\managedby.txt"
Clear-Content $exportlist
$Header = `
"Group ID Name" + "|" + "ManagedBy"
$Header | Out-File $exportlist -Append
$list = get-adgroup -properties name, managedby -filter {managedby -like "ML_*"} `
| Select name, managedby | Export-CSV $exportlist -NoType -Delimiter '|'
#Attempt 4
$MLgroupAll = Get-adgroup -Properties managedby, enabled, name -filter {managedby -like $name}
foreach ($group in $MLgroupAll) {
write-host $group.name + $group.managedby}
UPDATE: if i try to changed my $name variable it still doesn't work and gives another error.
$MLgroupAll = get-adgroup -Properties managedby, enabled, name -filter {managedby -eq $name}
foreach ($group in $MLgroupAll) {
$managed = $group.managedby
if ($managed -like "ML*"){
write-host $group.name + $group.managedby }
}
ERROR:
Get-ADGroup : Identity info provided in the extended attribute: 'ManagedBy' coul
d not be resolved. Reason: 'Cannot find an object with identity: 'ML*' under: 'D
C=we,DC=dirsrv,DC=com'.'.
#Paul: here is my error still:
Here is an example that works for me (orienting myself at your last try):
get-adgroup -filter * -Properties managedby | % {
if($_.managedby -like "CN=ML*"){
write-host $_.name + $_.managedby
}
}

Powershell - Get Last Logon

I have a quick script I am trying to reuse from getting computers lastlogon. Due to time constraints I am posting it here for assistance. I am trying to use the display name and even tried using the sam, but no luck.
$results = #()
$CompanyUsers = import-csv c:\bin\users.csv
foreach ($i in $CompanyUsers)
{
$results += Get-Aduser -Filter $i.sam -Properties * | select Name, Lastlogondate
#$results += Get-Aduser -Filter {displayname -eq $i.displayname} -Properties * | select Name, Lastlogondate
}
$results | export-csv c:\bin\Userslogon.csv
I get syntax errors. I can manually put in the values so I am thinking it has to do with data types extracted from the array. Suggestions would be appreciated!
SAM ERROR:
Get-Aduser : Error parsing query: 'xxx001' Error Message: 'syntax error' at position: '1'.
At C:\bin\Get-UserLastLogon.ps1:19 char:14
+ $results += Get-Aduser -Filter $i.sam -Properties * | select Name, Lastlogondat ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ParserError: (:) [Get-ADUser], ADFilterParsingException
+ FullyQualifiedErrorId : Error parsing query: 'kal001' Error Message: 'syntax error' at posi
tion: '1'.,Microsoft.ActiveDirectory.Management.Commands.GetADUser
DISPLAYNAME ERROR:
Get-Aduser : Property: 'displayname' not found in object of type:
'System.Management.Automation.PSCustomObject'.
At C:\bin\Get-UserLastLogon.ps1:20 char:17
+ $results += Get-Aduser -Filter {displayname -eq $i.displayname} -Properties ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Get-ADUser], ArgumentException
+ FullyQualifiedErrorId : Property: 'displayname' not found in object of type: 'System.Manage
ment.Automation.PSCustomObject'.,Microsoft.ActiveDirectory.Management.Commands.GetADUser
Thanks for the suggestions. I found a way to get this to work:
# Create array of users
$results = #()
$Users = Get-Content C:\bin\fullnames.txt
# Get last logon date
foreach($i in $Users)
{
$results += Get-ADUser -ldapfilter "(displayname=$i)" -Property * | Select-Object -Property name, samaccountname, lastlogondate
}
# Export results to csv file
$results | export-csv c:\bin\logonusers.csv
Try one of these:
Get-Aduser -Filter "samaccountname -eq '$i.sam'" -Properties *
Get-Aduser -Filter "displayname -eq '$i.displayname'" -Properties *
The samaccountname will be faster, since that's an indexed property.
# Create array of users
$results = #()
$Users = Get-Content C:\bin\fullnames.txt
# Get last logon date
foreach($i in $Users)
{
$results += Get-ADUser -ldapfilter "(displayname=$i)" -Property * | Select-Object -Property name, samaccountname, lastlogondate
}
# Export results to csv file
$results | export-csv c:\bin\logonusers.csv