Get PowerShell to search extension attribute in AD - powershell

I'm trying to get PowerShell to import a CSV file that has a list of employee ID numbers and search AD for those numbers. If I run it the way it is now I get no results, I just get a blank CSV files it creates at the end of the process.
If I tell PowerShell to Write-Host $.ID it will give me a list of all the IDs that are in the imported CSV. So it seems that it's able to read the file just fine. I have also tested and if I replace Get-ADUser -Filter "extensionAttribute13 -like '$.ID'" with an actual ID number instead of $_.ID I get the result I'm looking for.
I'm not 100% sure what I'm missing in getting the employee numbers passed along to return the data I need.
Import-Csv C:\temp\emplid.csv |
ForEach {
Get-ADUser -Filter "extensionAttribute13 -like '$_.ID'" -Server "dc01" -Properties * | select extensionAttribute13, Name, Description
} | Export-Csv C:\temp\employees.csv -NoTypeInformation
Any help would be extremely appreciated.
Thank you!

You need to put a subexpression $() around $_.ID:
Import-Csv C:\temp\emplid.csv |
ForEach {
Get-ADUser -Filter "extensionAttribute13 -like '$($_.ID)'" -Server "dc01" -Properties * | select extensionAttribute13, Name, Description
} | Export-Csv C:\temp\employees.csv -NoTypeInformation

Related

look up user in AD using text file and export to CSV

Trying to look up a user by DisplayName from a txt file and trying to export it to a CSV.
The expected goal is to have a list of LastName, FirstName (displaynames.txt), have it return an exported CSV file with the information in the "Format-Table" within the code.
Here's the code I've tried
ForEach ($DN in (Get-Content -Path c:\displaynames.txt))
{ Get-ADUser -Filter { displayName -like "*$DN*" } -SearchBase "DC=DOMAIN,DC=NET" | Format-Table Surname,GivenName,SamAccountName,UserPrincipalName | Out-File C:\UserAD.csv
}
the file returns blank. Thoughts? much appreciated in advance
Give this a try, as Jonathan mentioned in his comment, Format-Table is meant to display formatted information to the console and, even though you can use it to export the formatted information to a file it will definitely not be a CSV.
The other potential problem on your code, is that C:\UserAD.csv is getting replaced on each iteration of the loop because Out-File doesn't have the -Append switch.
Get-Content -Path c:\displaynames.txt | ForEach-Object {
if(-not [string]::IsNullOrWhiteSpace($_))
{
Get-ADUser -LDAPFilter "(displayName=*$_*)" -SearchBase "DC=NWIE,DC=NET"
}
} | Select-Object Surname, GivenName, SamAccountName, UserPrincipalName |
Export-Csv path/to/csv.csv -NoTypeInformation

Issues exporting powershell to CSV

It has been many moons since I have last done this and I am having problems exporting some commands to CSV. The biggest one that is getting me right now is
$ADGroupList = Get-ADGroup -Filter * -property * | Select Name -ExpandProperty Name | Sort
ForEach($Group in $ADGroupList)
{
Write-Host "Group: "$Group.Name
Get-ADGroupMember -Identity $Group | Select Name -ExpandProperty Name | Sort
Write-Host ""
}
Export-Csv -path "c:\Temp\test675.csv"
Works fine with out trying to export but the second I try to export the command will run and either generate a blank file or no file at all.
I am able to run other commands with out a issue exporting them to csv. Thanks for any help in advance.
Tim,
From what I can see you're not giving Export-Csv anything to write. Try this:
$ADGroupList = Get-ADGroup -Filter * -property * | Select Name -ExpandProperty Name | Sort
ForEach($Group in $ADGroupList)
{
Write-Host "Group: "$Group.Name
Get-ADGroupMember -Identity $Group |
Select Name -ExpandProperty Name |
Sort |
Export-Csv -path "c:\Temp\test675.csv"
Write-Host ""
}
I'd test this but I don't have access to ActiveDirectory.
Also the Write-Hosts you probably don't want in the .csv file as they won't play well with the format, headers & columns.
HTH

Escape apostrophes from variable in powershell

I have the following script set up, and it works as intended....except for users with apostrophes in their email.
$users = get-content C:\Filename.csv
$results = Foreach ($user in $users)
{
get-aduser -filter "EmailAddress -like '$user'" -properties CanonicalName,LastLogon,Name |
select Name,#{N="Thing";E={$_.DistinguishedName.Split(',')[-4]}},#{N="Place";E={$_.DistinguishedName.Split(',')[-5]}},#{N="Last Logon";E `
={[DateTime]::FromFileTime($_.Lastlogon)}}
}
$results | Export-Csv C:Filename.csv -NoTypeInformation
Does anyone know how to escape the apostrophe in an email like example_o'connor#example.com? Whenever I run the above script it always errors out on email addresses like the one above.
Edit: My csv file is a single column of email addresses with no header.
Edit 2: Sorry to waste everyone's time. Turns out the script was working fine, along with some of the suggestions in this thread such as adding "" "" around my variable, but it was that I was testing against a list where not all the values were correct so that is my fault. Thank you everyone for your time.
Try this...
Since you are using a CSV, I imagine you've piped them from another AD cmdlet.
Get-Member is a great tool here.
$users | Get-Member will output TypeName: CSV:Selected.Microsoft.ActiveDirectory.Management.ADUser
However, this is not a String type which the Filter parameter in ADUser needs.
So to convert this...
$selection | Get-Member will output TypeName: System.String.
The other portion is to make sure that the -Filter parameter in Get-ADUser is expanding the strings properly one-by-one, since Get-ADUser's -Filter parameter cannot deal with String Arrays.
$users = Import-Csv C:\filename.csv
$selection = ($users.emailaddress)
foreach ($user in $selection)
{
get-aduser -filter {EmailAddress -eq $user} -properties CanonicalName,LastLogon,Name |`
select Name,#{N="Thing";E={$_.DistinguishedName.Split(',')[-4]}},`
#{N="Place";E={$_.DistinguishedName.Split(',')[-5]}},`
#{N="Last Logon";E={[DateTime]::FromFileTime($_.Lastlogon)}}
}

Move AD user based on their employeeID in csv file

I'm attempting to move AD users to different ou's based on a CSV file of employee numbers. I've searched around and I have found a suggestion and tried this code:
Import-Module ActiveDirectory
$TargetOU = "OU=Math,OU=Students,DC=domain,DC=net"
$IDs = Import-CSV "c:\testids.csv" | Select -ExpandProperty employeeID
Get-ADUser -filter * -Properties employeeID | Where { $IDs -contains $_.employeeID } |
Move-ADObject -TargetPath $TargetOU
My csv file looks like this
employeeID
11111
22222
33333
It runs with no errors. But the users never move. Im running Server 2012R2.
Any suggestions? Am I on the wrong track or completely off in left field?
Try this
Import-Module ActiveDirectory
$TargetOU = "OU=Math,OU=Students,DC=domain,DC=net"
$IDs = Import-CSV "c:\testids.csv" | Select employeeID
$IDs | % { Get-ADUser -Filter { employeeID -eq $_.employeeID } -Property employeeID |
Move-ADObject -TargetPath $TargetOU }
Sorry, I pushed 'Enter' too quickly. This has your CSV saved as the $IDs object before you start. I think your pipes were a little out of order. Let me know if this works, and if it doesn't I'll try again.
Ok, I'm on the bandwagon of I want to be sure your finding the correct users first. Theory being that Move-ADObject is not getting any input.
First I would do this to check the CSV file contents.
Get-Content "c:\testids.csv" | Select -Skip 1 | ForEach-Object{"'$_'"}
Then assuming that is working what is the result of this command?
$IDs | ForEach-Object{Get-ADUser -Filter "employeeID -eq '$_'" -Property employeeID
Update from Comments
I wonder now if you are looking at the wrong AD Attribute. Maybe it should be EmployeeNumber.
$IDs | ForEach-Object{Get-ADUser -Filter "employeeNumber -eq '$_'" -Property employeeNumber
Give that a try and see if that is what you need?
Also should try and verify that you have no white-space or special characters in the actual employeeid
"'$(Get-Aduser accountthathasid -properties employeeid | select -expand employeeid)'"
I'm willing to bet that the whole issue you're running into is that Get-ADUser is returning no user objects.
<Previous answer removed>
Edit: Ok, I give up, this makes no sense. I now can not find my own user by looking for it by EmployeeID. I think there may be some issues searching by employeeID because this returns nothing:
$me = get-aduser $env:USERNAME -Properties EmployeeID
Get-ADUser -filter "EmployeeID -eq '$($me.EmployeeID)'" -Properties EmployeeID
I verified that $me does in fact contain my ADUser object info, including my EmployeeID. I thien tried:
Get-ADUser -filter "UserPrincipalName -eq '$($me.UserPrincipalName)'"
This did work, so I am sure that my format works. At this point, I withdraw and wish you luck.

How do I get Powershell to output Get-ADUser -Filter * as comma delimited?

I have a simple Powershell script that I want to use to grab all the users in AD and show specific properties. Here is the heart of my script:
$id = "*"
Get-ADUser -Filter {SAMAccountName -like $id} -Properties * | Select-Object -Property SAMAccountName,Name,PasswordNeverExpires,LockedOut,PasswordLastSet,LastLogOnDate,CanonicalName
The full script has an input parameter to set $id so that it can be a single ID, a list of IDs (such as "bsmith, jdoe, gmanning"), or * to get all accounts.
Here's my problem: When using, *, I need this to output as comma delimited.
Here's the catch: The output cannot be to a CSV file--or any other type of file.
The reason being is that I'm writing this script to be used on N-Enable's N-Central monitoring suite of software. You don't need to know N-Central to help with my problem, just understand that N-Central uses its own software to run Powershell scripts on clients and returns the results into a txt file that cannot be changed to a csv file (or formatted in any other way than what it has hard-coded).
What this means is that my results have to either be what would show up on the screen or in a variable (such as $results=Get-ADUser -Filter * ....). I cannot output to any type of file, which leaves out Export-CSV as an option.
I've tried other types of formatting to no avail (such as with -f). The issue seems to be with the way Powershell grabs all AD Users using the * wildcard. It seems to grab them all as one big object, so I am unable to get my output to have a comma between all the properties so that I get a comma-delimited output. Thus, when I get the results back from N-Central as a .txt file, all the data is there, but there are no commas in between the properties for me to then open the .txt file as comma-delimited in Excel (or tab-delimited for that matter).
Does anyone have a solution that will allow me to format Get-ADUser -filter * so that it is comma-delimited without using export to file?
UPDATE: Ok, I thought I was keeping things easy by not posting my full script but it seems I've done the opposite. So, below is my full script. Anyone should be able to run this to see the results:
function Get-ADUserInfo
{
[CmdletBinding()]
param(
#[Parameter(Mandatory=$True)]
[string[]]$Users= '*'
)
Begin {
$maxPasswordAge = (Get-ADDefaultDomainPasswordPolicy).MaxPasswordAge.Days
$Headers="ID, Name, Password Never Expires?, Locked Out, Password Last Set, Expiry Date, Last Logon Date, OU Path"
}
Process {
foreach ($id in $Users)
{
$results=Get-ADUser -Filter {SAMAccountName -like $id} -Properties * | select -property SAMAccountName,Name, PasswordNeverExpires,LockedOut,PasswordLastSet,(#{Expression={$_.PasswordLastSet.AddDays($maxPasswordAge)}}), LastLogOnDate,CanonicalName | `
ConvertTo-CSV -NoTypeInformation
}
}
End {
$Headers
$results
}
}
Get-ADUserInfo -Users
Some notes:
When calling Get-AdUserInfo -Users, the script needs to work by entering a single ID, *, or multiple IDs separated by a comma when using the -Users parameter.
Using ConvertTo-CSV solved my biggest problem, comma separated output,thanks all.
I'd like to get rid of the headers that are auto-created as well ("SAMAccountName","Name","PasswordNeverExpires","LockedOut","PasswordLastSet","$_.PasswordLastSet.AddDays($maxPasswordAge)","LastLogOnDate","CanonicalName"). How can I do that? I've tried -skip 1 but that doesn't work with * and removes everything (including the data) if used with a single ID or IDs separated with commas. I can't get -ExpandProperty to work either. Adding format-table -hidetableheaders at the end doesn't do anything as well
So you could use something like this then
$props = "SAMAccountName","Name","PasswordNeverExpires","LockedOut","PasswordLastSet","LastLogOnDate","CanonicalName"
$results = Get-ADUser -Filter * -Properties $props | Select $props | ConvertTo-Csv -NoTypeInformation
This uses the $props array to make the actual query readable and enforce property order. Most of those properties are returned by default, like samaccountname, so it is not required to specify them but no harm done.
$results would contain a quoted comma delimited output. If the quotes bother you they should be removed with a simple -replace
$results = $results -replace '"'
Aside
As others have mentioned you are wasting time using -Properties * you should only return the properties that you need. Which is, again, why I used $props.
Update from comments
If you want to remove the header column you just need to -Skip that from the output. At the end of the code that populates results just add Select-Object
$results = Get-ADUser -Filter * -Properties $props | Select $props | ConvertTo-Csv -NoTypeInformation | Select-Object -Skip 1
Also to cover your calculated property the easiest way that I have found so far is to add another Select-Object. Not the way I would want to but for now it works.
$results = Get-ADUser -Filter * -Properties $props |
Select $props | Select-Object *,#{L="pWD";Expression={$_.PasswordLastSet.AddDays($masPasswordAge)}} |
ConvertTo-Csv -NoTypeInformation | Select-Object -Skip 1
Game Changer
So you made some pretty big changes to your example by including your function. Try this on for size now.
function Get-ADUserInfo
{
[CmdletBinding()]
param(
#[Parameter(Mandatory=$True)]
[string[]]$Users= '*'
)
Begin{
$results = #()
$maxPasswordAge = (Get-ADDefaultDomainPasswordPolicy).MaxPasswordAge.Days
$Headers= #{Label="ID";Expression={$_.SAMAccountName}},
#{Label="Name";Expression={$_.Name}},
#{Label="Password Never Expires?";Expression={$_.PasswordNeverExpires}},
#{Label="Locked Out";Expression={$_.LockedOut}},
#{Label="Password Last Set";Expression={$_.PasswordLastSet}},
#{Label="Expiry Date";Expression={$_.PasswordLastSet.AddDays($maxPasswordAge)}},
#{Label="Last Logon Date";Expression={$_.LastLogOnDate}},
#{Label="OU Path";Expression={$_.CanonicalName}}
}
Process{
foreach ($id in $Users){
$results += Get-ADUser -Filter {SAMAccountName -like $id} -Properties PasswordNeverExpires,LockedOut,PasswordLastSet,LastLogOnDate,CanonicalName | select $Headers
}
}
End{
$results | ConvertTo-CSV -NoTypeInformation
}
}
Get-ADUserInfo -Users
$Headers= contains a collection of calculate properties most of which are there the change the header. It does not need to be done this was and you could have just manually added a header line before the output of contents. This solution however is more in line with what PowerShell is capable of.
We collect all of the users in the array $results and in the End block convert that to CSV output which would not contain your custom headers.
$id = "*"
$userlist = Get-ADUser -Filter {SAMAccountName -like $id} -Properties SAMAccountName,Name,PasswordNeverExpires,LockedOut,PasswordLastSet,LastLogOnDate,CanonicalName | ConvertTo-CSV -NoTypeInformation
$userlist will be an array of users stored in CSV formatted lines
Edit: Combined -Properties * | Select [propertylist] and get rid of the pull of all properties.
Edit: included -NoTypeInformation so that the output is pure CSV.
Note: Something should be done about the filter.