I'm trying to get a list of enabled users employee numbers (employeenumber) and their email addresses (mail) and format it without headers and with a single space between the fields using PowerShell.
The script works for the most part, but if the employeenumber field is empty I want to exclude it. It doesn't matter if the email address is empty. What I get now is blank spaces if the employee number doesn't exist.
My script:
Get-ADUser -Filter 'enabled -eq $true' -Properties employeenumber, mail |
select -Property employeenumber, mail |
Format-Table -HideTableHeaders |
Out-File allusers_email.txt
I've tried putting Get-ADUser into an array and doing a foreach, but the output is empty. I use PowerGUI and when stepping through the foreach the value of employeenumber is the distinguished name of the user and the output file is blank when the script finishes.
I've also used the following to try to remove the extra spaces, but it's not working.
(gc allusers_email.txt) |
? {$_.Trim() -ne ""} |
Set-Content allusers_email.txt
Using Kiril solution I was able to get what I needed. I now need to change this so that only user objects that have changed today will be output. I've added a variable to contain today's date and I believe I should use Get-ADObject and filter on the whenchanged attribute. However, I get errors. What am I missing from the Get-ADObject command?
$dte=Get-Date
Get-ADUser -Filter 'enabled -eq $true' -Properties employeenumber, mail, ipPhone, mobile |
Where { $_.employeenumber -ne $null } |
Get-ADObject -Filter 'whenchanged -eq $dte'
Select #{Name='Custom';Expression={('{0} {1} {2} {3}' -f $_.employeenumber,$_.mail,$_.ipPhone,$_.mobile).Trim()}} |
Select -ExpandProperty Custom |
Out-File EMailStream.txt
I ended up going with the following script:
$dte=Get-Date -Hour 0 -Minute 00 -Second 00
Get-ADUser -Filter 'enabled -eq $true' -Properties whenchanged, employeenumber, mail, ipPhone, mobile |
Where { $_.employeenumber -ne $null -and $_.whenchanged -gt $dte } |
Select #{Name='Custom';Expression={('{0} {1} {2} {3}' -f $_.employeenumber,$_.mail,$_.ipPhone,$_.mobile).Trim()}} |
Select -ExpandProperty Custom |
Out-File EMailStream.txt
Try to add filter condition, and create combined property value, like so:
Get-ADUser -Filter 'enabled -eq $true' -Properties employeenumber, mail |
Where { $_.employeenumber -ne $null } |
Select #{Name='Custom';Expression={('{0} {1}' -f $_.employeenumber,$_.mail).Trim()}} |
Select -ExpandProperty Custom |
Out-File allusers_email.txt
Related
Im trying to write a script that goes through a CSV-File, searches up the Username in our AD and then gives me these users, that have a specific E-Maildomain and hasn't logged in for the last 90 days.
Here's what I got so far:
import-csv C:\pathtofile\user.csv | ForEach-Object {
Get-ADUser $_.SamAccountName -Filter "EMailAddress -like '*#thedomain.com'" -Properties SamAccountName,LastLogonDate | Where { ($_.LastLogonDate -lt (Get-Date).AddDays(-90)) -and ($_.LastLogonDate -ne $NULL)} | Sort | Select Name,SamAccountName,LastLogonDate
}
But it gives me this weird error:
Get-ADUser : A positional parameter cannot be found that accepts argument 'Username'.
I tried to put the E-Mailsorting into my where-statement, but it was not able to find any users then...
Can you guys may see what I'm doing wrong?
Thank you for your help.
Kind regards,
Gabe
You cannot use parameter -Filter together with -Identity.
(using Get-ADUser $_.SamAccountName implicitely uses the -Identity parameter)
To filter out only users that are in your CSV file AND that have a specific domain in their email address, you can do:
$refDate = (Get-Date).AddDays(-90).Date # set to midnight
$result = Import-Csv -Path 'C:\pathtofile\user.csv' | ForEach-Object {
$userSam = $_.SamAccountName
try {
$user = Get-ADUser $userSam -Properties EmailAddress, LastLogonDate -ErrorAction Stop
if (($user.LastLogonDate) -and $user.LastLogonDate -lt $refDate -and
$user.EmailAddress -like '*#thedomain.com') {
$user | Select-Object Name,SamAccountName,EmailAddress,LastLogonDate
}
}
catch {
Write-Warning "User '$userSam' not found"
}
}
To filter out all users that have a specific domain in their email address, so not using the csv at all, you can do:
$refDate = (Get-Date).AddDays(-90).Date # set to midnight
$result = Get-ADUser -Filter "EmailAddress -like '*#thedomain.com'" -Properties EmailAddress, LastLogonDate |
Where-Object { ($_.LastLogonDate) -and $_.LastLogonDate -lt $refDate } |
Select-Object Name,SamAccountName,EmailAddress,LastLogonDate | Sort-Object Name
# show the result on screen
$result | Format-Table -AutoSize
# and/or save to a new csv file
$result | Export-Csv -Path 'C:\pathtofile\filteredusers.csv' -NoTypeInformation
I have a list of users in a CSV, but I need to collect the SamAccount attribute from each user by name in the ad.
CSV model
Script
Get-ADObject -Filter 'ObjectClass -eq "user" -and userAccountControl -eq "512"' -Properties * | Select-Object SamAccountName,CN,DisplayName, | Export-CSV -Path C:\Temp\UserAccounts.csv -Encoding UTF8 -NoTypeInformation
I'm a little lost I don't know how to do a foreach using name
I am trying but without success.
Trying to get samaccountname based on Name on csv file.
Import-Csv -Path C:\Temp\userteste.csv | foreach-Object {Get-ADUser -Filter {Name -like $_.name} -Properties Name | Select-Object samAccountName}
and export to csv file.
Why use Get-ADObject and not Get-ADUser for this? The latter gives you more of the desired properties you need in the CSV.
As aside, it is wasteful to do -Properties * if all you want is a small set of user attributes.
Something like this should work:
Get-ADUser -Filter "Enabled -eq $true" -Properties DisplayName, CN |
Select-Object SamAccountName, CN, DisplayName |
Export-Csv -Path C:\Temp\UserAccounts.csv -Encoding UTF8 -NoTypeInformation
As per your comment you need to get some extra attributes of the users listed in the CSV, you can do this:
Import-Csv -Path C:\Temp\userteste.csv | ForEach-Object {
Get-ADUser -Filter "Name -like '$($_.Name)'" -Properties DisplayName, CN |
Select-Object SamAccountName, CN, DisplayName
} | Export-Csv -Path C:\Temp\UserAccounts.csv -Encoding UTF8 -NoTypeInformation
Hope that helps
I'm trying to stitch together two lines of PowerShell, but I just can't figure the syntax. There is a post that sounds like it might be what I need, but it isn't using -LDAPFilter.
To generate a list of AD users created in the last 100 days, I use
$now = ((Get-Date).AddDays(-100)).Date
$users = Get-ADUser -Filter {whenCreated -ge $now} -Searchbase "OU=staff,OU=SMUC_Users,DC=stmarys,DC=ac,DC=ie" |
Where-Object { $_.Enabled -eq 'True' }
And this code from "How to get ALL AD user groups (recursively) with Powershell or other tools?" does the next step, which is to find all the groups that a user is a member of:
$username = 'd.trump'
$dn = (Get-ADUser $username).DistinguishedName
Get-ADGroup -LDAPFilter ("(member:1.2.840.113556.1.4.1941:={0})" -f $dn) |
select -Expand Name
but I can't pipe the output of the first into the second to get an overall list.
Get-ADUser -Filter {whenCreated -ge $now} -Searchbase "OU=staff,OU=SMUC_Users,DC=stmarys,DC=ac,DC=ie" |
Where-Object { $_.Enabled -eq 'True' } |
Select-Object DistinguishedName |
Get-ADGroup -LDAPFilter ("(member:1.2.840.113556.1.4.1941:={0})" -f $_) |
select -expand Name
The error message is:
Get-ADGroup : The search filter cannot be recognized
I thought the second code snippet extracted the distingushed name and supplied it to the filter, and that is what I have tried to do in the pipeline.
You are missing ForEach-Object (alias %).
The following code should work:
Get-ADUser -Filter {whenCreated -ge $now} -SearchBase "OU=staff,OU=SMUC_Users,DC=stmarys,DC=ac,DC=ie" `
| Where-Object { $_.Enabled -eq 'True' } `
| %{Get-ADGroup -LDAPFilter ("(member:1.2.840.113556.1.4.1941:={0})" -f $_.DistinguishedName)} `
| Select-Object -ExpandProperty Name
If you want to output both user and group information you can expand the code like this:
Get-ADUser -Filter {whenCreated -ge $now} -SearchBase "OU=staff,OU=SMUC_Users,DC=stmarys,DC=ac,DC=ie" `
| Where-Object { $_.Enabled -eq 'True' } `
| %{$group = Get-ADGroup -LDAPFilter ("(member:1.2.840.113556.1.4.1941:={0})" -f $_.DistinguishedName);Write-Output $_.UserPrincipalName $group.Name}
I'm trying to pull a list of users (first name and last), their email addresses, and which container they're in, but unfortunately it's not coming up with the data I need. I can get most of the information, just not the container name.
Get-ADUser -SearchBase 'DC=DOMAINNAME,DC=COM' -Filter {(mail -ne "null") -and (Enabled -eq "true")} -Properties emailAddress |
Select givenName,surName,OU,emailAddress |
Format-Table -AutoSize |
Out-File 'C:\Users\username\Desktop\Lists\Users_List.txt'
You're looking for the attribute DistinguishedName, but to just get the OU you would have to do some formatting. If you ran Get-ADUser | Get-Member you would see there is no property called OU.
Get-ADUser `
-SearchBase 'DC=DOMAINNAME,DC=COM' `
-Filter {(mail -ne "null") -and (Enabled -eq "true")} `
-Properties emailAddress `
| Select givenName,surName,#{Name='OU';Expression={$_.DistingishedName.Replace("CN=$($_.Name),","")}},emailAddress `
| Format-Table -AutoSize `
| Out-File 'C:\Users\username\Desktop\Lists\Users_List.txt'
Article on Understanding PowerShell Custom Properties with the Select-Object cmdlet
I would change your mail filters to $false, and $true. I don't have a computer with the AD module installed on it to test out my answer, otherwise I would have provided more.
The command line is returning nothing when I'm using it.
I've already changed Name to DisplayName or CN but this wasn't working too.
Import-Csv "D:\Temp\userExcelRights.txt" |
%{ Get-ADUser -Filter {Name -eq "*$_*"} } |
Select Name,Enabled,SamAccountName,DistinguishedName
The CSV file contains the full name of users.
The -eq operator doesn't support wildcard matches, you need to use the -like operator for that, and you must select a property from the objects that Import-Csv procuces. Also, avoid scriptblock syntax for Get-ADUser filters. Replace
{Name -eq "*$_*"}
with
"Name -like '*$($_.Name)*'"
If the subexpression doesn't work for you, you may need to expand the Name property before feeding it into the loop:
Import-Csv 'D:\Temp\userExcelRights.txt' |
select -Expand Name |
%{ Get-ADUser -Filter "Name -eq '*$_*'" } |
...
With this command it's working:
$data=#(Import-Csv "D:\Temp\userExcelRights.txt").Name
$data | %{ Get-ADUser -Filter "name -like '*$_*'" } |
Select Name,Enabled,SamAccountName,DistinguishedName
Thanks to Ansgar Wiechers.