Get-ADUser account name whose email address matches any of the emails indicated in csv file - powershell

I have a comma-separated csv file as below (first row is the header):
category;email.1;email.2;email.3;email.4;email.5;email.6
category1;sample#gmail.com;;;;;
category2;;;sample2#gmail.com;;;
category3;;sample3#gmail.com;;sample44#hotmail.com;;sample55#gmail.com
and so on...
Now I import it:
$emails = Import-CSV -Encoding Default -Delimiter ";" "c:\temp\myFile.csv"
And finally, for each row in the csv I want to get the AD user account name whose email address matches any from email.1 to email.6
So I try this using a foreach loop but I have no idea what have to put within it to get what I want.
$emails | foreach {
$userAccountName = Get-ADUser -filter {something}
# do some stuff with $userAccountName
}
Note: I would like a generic solution taking into account that in future can be more than 6 emails by category. Also take into account that some emails can be empty for the category.

Once imported you can enumerate the headers matching a pattern
$emails = Import-CSV -Encoding Default -Delimiter ";" "c:\temp\myFile.csv"
$EmailHeaders = ($Emails[0].psobject.Properties|Where-Object Name -like 'email.*').Name
ATM this returns:
> $EmailHeaders
email.1
email.2
email.3
email.4
email.5
email.6
Nest foreachs's to iterate the emails per row which are populated.
Get-ADUser commented out for testing
foreach($Row in $Emails){
foreach($EmailHeader in $EmailHeaders){
if($Email=$Row.$EmailHeader){
[PSCustomObject]#{
Category = $Row.Category
Email_x = $EmailHeader
Email = $Email
SamAccountName= $Null #(Get-ADUser -Filter {EmailAddress -eq "$Email"} -Properties SamAccountName).SamAccountName
}
}
}
}
Category Email_x Email SamAccountName
-------- ------- ----- --------------
category1 email.1 sample#gmail.com
category2 email.3 sample2#gmail.com
category3 email.2 sample3#gmail.com
category3 email.4 sample44#hotmail.com
category3 email.6 sample55#gmail.com

Related

Check if a value exists in one csv file and add static text to another csv field with Powershell

I need to check if the column value from the first csv file, exists in any of the three other csv files and return a value into a new csv file, in order of precedence.So if the username field from allStaff.csv exists in the list of usernames in the sessionVPNct.csv file, put the static text into the final csv file as 'VPN'. If it does not exist, check the next csv file: sessionCRXct.csv then put the static text 'CRX', if not check the last csv file: sessionTMSct.csv then put the static text: TM if not the put the static text 'none' into the final csv file.
I have four csv files as below:
1. allStaff.csv
2. VPN.csv
3. CRX.csv
4. TMS.csv
I have imported the csv files into variables as below:
$allUsers = Import-Csv -Path "C:\allStaff.csv"
$vpn = Import-Csv -Path "C:\VPN.csv" | Select-Object -ExpandProperty UserName
$crx = Import-Csv -Path "C:\CRX.csv" | Select-Object -ExpandProperty UserName
$tms = Import-Csv -Path "C:\TMS.csv" | Select-Object -ExpandProperty UserName
The $allUsers variable displays the following:
Firstname LastName Username Position Area
--------- -------- -------- -------- ----
Joe Bloggs jbloggs Gardener Maintenance
Jim Smith jsmith Accountant Finance
Bob Seger bseger HR Advisor Human Resources
Adam Boson aboson Customer Support IT
Adele bree abree Payroll Finance
The $vpn variable displays the following:
Username
--------
jbloggs
jsmith
The $crx variable displays the following:
Username
--------
jbloggs
jsmith
bseger
The $tms variable displays the following:
Username
--------
jbloggs
jsmith
bseger
aboson
Then I have the following line to start the result csv file
$result = $allUsers | Select-Object *,ConnectionMethod
Not quite sure how to do the final query, which I believe should be an if else loop to go through all rows in the $result variable, and check the other csv if the username field exists, then return the static text.
$result | Export-Csv -Path "C:\allStaffConnections.csv"
This is how I need the final allStaffConnections.csv file to be displayed.
Firstname LastName Username Position Area ConnectionMethod
--------- -------- -------- -------- ---- --------------
Joe Bloggs jbloggs Gardener Maintenance VPN
Jim Smith jsmith Accountant Finance VPN
Bob Seger bseger HR Advisor Human Resources CRX
Adam Boson aboson Customer Support IT TMS
Adele bree abree Payroll Finance none
Am I on the right track with the below code?
$allUsers = Import-Csv -Path "C:\allStaff.csv"
$vpn = Import-Csv -Path "C:\VPN.csv" | Select-Object -ExpandProperty UserName
$crx = Import-Csv -Path "C:\CRX.csv" | Select-Object -ExpandProperty UserName
$tms = Import-Csv -Path "C:\TMS.csv" | Select-Object -ExpandProperty UserName
$vpnText = 'VPN'
$crxText = 'CRX'
$txsText = 'TMS'
$noneText = 'none'
$allUsersExtended = $allUsers | Select-Object *,ConnectionMethod
$results = $allUsersExtended.ForEach(
{
if($vpn -Contains $PSItem.UserName) {
# add $vpnText to ConnectionMethod column for that row in the $result
$PSItem.ConnectionMethod = $vpnText
}elseif($crx -Contains $PSItem.UserName) {
# add $crxText to ConnectionMethod column for that row in the $result
$PSItem.ConnectionMethod = $crxText
}elseif($tms -Contains $PSItem.UserName) {
# add $txsText to ConnectionMethod column for that row in the $result
$PSItem.ConnectionMethod = $tmsText
}else {
# add $noneText to ConnectionMethod column for that row in the $result
$PSItem.ConnectionMethod = $noteText
}
})
$results | Export-Csv -Path "C:\allStaffConnections.csv" -NoTypeInformation
This gives me an empty allStaffConnections.csv file.
I have run the code line by line and can get as far as:
$allUsersExtended = $allUsers | Select-Object *,ConnectionMethod
Which gives me the extra column "ConnectionMethod", but after running the loop, it gives me an empty allStaffConnections.csv file.
here is one way to do the job. [grin] it presumes that you only want to 1st connection type found. if you want all of them [for instance, JBloggs has all 3 types listed], you will need to concatenate them.
what it does ...
fakes reading in the CSV files
when ready to use real data, comment out or remove the entire #region/#endregion section and use Get-Content.
iterates thru the main collection
uses a switch to test for membership in each connection type list
this breaks out of the switch when it finds a match since it presumes you only want the 1st match. if you want all of them, then you will need to accumulate them instead of breaking out of the switch block.
sets the $ConnectionType as appropriate
builds a PSCO with all the wanted props
this likely could be shortened by using Select-Object, a wildcard property selector, and a calculated property.
sends it out to the $Results collection
shows it on screen
saves it to a CSV file
the code ...
#region >>> fake reading in CSV files
# in real life, use Import-CSV
$AllUsers = #'
FirstName, LastName, UserName, Position, Area
Joe, Bloggs, jbloggs, Gardener, Maintenance
Jim, Smith, jsmith, Accountant, Finance
Bob, Seger, bseger, HR Advisor, Human Resources
Adam, Boson, aboson, Customer Support, IT
Adele, bree, abree, Payroll, Finance
'# | ConvertFrom-Csv
$Vpn = #'
UserName
jbloggs
jsmith
'# | ConvertFrom-Csv
$Crx = #'
UserName
jbloggs
jsmith
bseger
'# | ConvertFrom-Csv
$Tms = #'
UserName
jbloggs
jsmith
bseger
aboson
'# | ConvertFrom-Csv
#endregion >>> fake reading in CSV files
$Results = foreach ($AU_Item in $AllUsers)
{
# this presumes you want only the 1st connection type found
# if you want all of them, then you will need to concatenate them
switch ($AU_Item.UserName)
{
{$_ -in $Vpn.UserName}
{
$ConnectionType = 'VPN'
break
}
{$_ -in $Crx.UserName}
{
$ConnectionType = 'CRX'
break
}
{$_ -in $Tms.UserName}
{
$ConnectionType = 'TMS'
break
}
default
{
$ConnectionType = 'None'
}
}
[PSCustomObject]#{
FirstName = $AU_Item.FirstName
LastName = $AU_Item.LastName
UserName = $AU_Item.UserName
Position = $AU_Item.Position
Area = $AU_Item.Area
ConnectionTYpe = $ConnectionType
}
}
# on screen
$Results
# send to CSV
$Results |
Export-Csv -LiteralPath "$env:TEMP\brokencrow_-_UserConnectionType.csv" -NoTypeInformation
truncated on screen output ...
FirstName : Joe
LastName : Bloggs
UserName : jbloggs
Position : Gardener
Area : Maintenance
ConnectionTYpe : VPN
[*...snip...*]
FirstName : Adele
LastName : bree
UserName : abree
Position : Payroll
Area : Finance
ConnectionTYpe : None
the CSV file content from brokencrow_-_UserConnectionType.csv ...
"FirstName","LastName","UserName","Position","Area","ConnectionTYpe"
"Joe","Bloggs","jbloggs","Gardener","Maintenance","VPN"
"Jim","Smith","jsmith","Accountant","Finance","VPN"
"Bob","Seger","bseger","HR Advisor","Human Resources","CRX"
"Adam","Boson","aboson","Customer Support","IT","TMS"
"Adele","bree","abree","Payroll","Finance","None"

How to look for Active Directory group name from csv in PowerShell?

If I have a .csv:
ClientCode,GroupCode
1234,ABC
1234,DEF
1235,ABC
1236,ABC
and I want to get a hashtable with ClientCode as key, and values to be all AD groups with ClientCode in it, for example:
ClientCode GroupCode
---------- ---------
1234 ClientGroup_InAD_1234, some_other_client_1234
1235 ClientGroup_InAD_1235, some_other_client_in_AD_1235
1236 ClientGroup_InAD_1236
How do I go about this?
Essentially, I have client groups in Active Directory and each client has a code which is the same as the 'ClientCode' in the csv. For example, I might have a client called 'Bob' which I have assigned a code '1234' to it. Therefore, the Group for Bob in the AD would be 'Bob_1234'. Essentially I want to be able to search for whatever groups have ClientCode in them. So i want to search for the all the AD groups that have '1234'. This would return 'Bob_1234' and whatever group in the AD also has '1234' in its name.
So far I have tried:
$clientTable = #{}
foreach($rec in $csv_data) {
$groups = #(get-adgroup -Filter "name -like '*$($rec.clientcode)_*'")
write-host "Found $($groups.count) group(s) for: $($rec.clientcode)"
$clientTable[$ClientCode] = #($groups)
}
$clientTable
but I'm not getting my desired output
You can use the loop like this. You will need to search with a * at the beginning of the name you are looking to find via the Filter.
foreach($rec in $csv) {
$clientCode = "*_$($rec.ClientCode)"
if (!($clientTable.ContainsKey($clientCode))) {
$names = Get-ADGroup -Filter 'Name -like $clientCode' | select Name
$clientTable[$clientCode] = $names -join ","
}
}
This will also check for any client IDs that have already been checked and ignore those.
If you want a hash table populated with the ClientCode value as the key name, you can do the following:
$clientTable = #{}
foreach($rec in $csv_data){
$groups = #(Get-ADGroup -Filter "Name -like '*_$($rec.ClientCode)'" | Select -Expand Name)
write-host "Found $($groups.count) group(s) for: $($rec.ClientCode)"
$clientTable[$rec.ClientCode] = $groups
}
$clientTable
Keep in mind here that each value in the hash table is an array of group names. If you want a single string with comma-delimited names, you can do $clientTable[$rec.ClientCode] = $groups -join "," instead.
You will need to de-duplicate the ClientCodes in the CSV before retrieving the groups.
Something like below should do it (assuming the ClientCode is always preceded by an underscore like in _1234 as shown in your examples)
$csv = Import-Csv -Path 'ClientGroupCodes.csv'
$clientTable = #{}
$csv | Select-Object -ExpandProperty ClientCode -Unique | ForEach-Object {
# $_ is a single clientcode in each iteration (string)
# get an array of goup names
$groups = #(Get-ADGroup -Filter "Name -like '*_$_'" | Select-Object -ExpandProperty Name)
Write-Host "Found $($groups.Count) group(s) for code : '$_'"
$clientTable[$_] = $groups -join ', '
}
$clientTable

Pulling a specific proxyaddress from AD using powershell

I have a list of users in a csv file. This list contains users whose primary SMTP address is not internal to our organization. These are mail users who are having email forwarded elsewhere.
They have a proxyaddress listed in AD that is on their AD account that points to the organization and this is what I am trying to get to. The problem is that the proxyaddresses does not put the email in the same location so I need to somehow extrapolate the email(s). that match a certain criteria.
What I would really like to get at is the first.last#example.com or first_last.example.com without the {smtp: } formatting.
I have been able to produce a list of proxyaddresses but again it is just a list.
$users = import-csv $BadEmailList | % {Get-ADUser $_.LoginID -Properties proxyaddresses}
Foreach ($u in $users) {
$proxyAddress = [ordered]#{}
$proxyAddress.add(“User”,$u.name)
For ($i = 0; $i -le $u.proxyaddresses.count; $i++)
{
$proxyAddress.add(“ProxyAddress_$i”,$u.proxyaddresses[$i])
} #end for
[pscustomobject]$proxyAddress |
Export-Csv -Path $ProxyAddressList -NoTypeInformation –Append -Force
Remove-Variable -Name proxyAddress } #end foreach
What I am trying to get is the something similar to the following:
User ProxyAddress_0
---- -----
User1 first.last#example.com
If you just want to find the specific AD user with a given proxyaddress, as the header implies, you should be able to use a LDAP filter like this:
Get-ADUser -LDAPFilter "(&(objectCategory=person)(objectClass=user)(|(proxyAddresses=*:first.last#example.com)))"

How do you export a list of PC names and a specific group membership of that endpoint using powershell?

I have a list of end points and we are trying to see if they have this specific group membership but I cannot figure out how to export the endpoint and the group its a member of.
$Groups = foreach ($pc in (Get-Content "C:\Users\*\Desktop\DefualtTest.csv")) {
try {
Get-ADComputer $pc -Properties memberof |
select -Expand memberof |
dsget group -samid |
? {$_ -match 'bit9'}
} catch {
Write-Output "$pc does not have bit9 group"
}
}
$Groups | Out-File "C:\Users\*\Desktop\testONE.csv"
trying to do this in comments is ... to difficult. [grin]
here's an example of what i mean by "do it one line at a time" in the foreach loop ...
# fake reading a list of systems from a text file
# in real life, use Get-Content
$ComputerList = #'
pc01
pc02
pc03
pc04
pc05
pc666
'# -split [environment]::NewLine
# fake getting a list of Computers & the groups they are in
# in real life, use Get-ADComputer & the ".MemberOf" property
$GroupMembershipLookup = #{
'pc01' = #('GroupA', 'GroupB')
'pc02' = #('GroupB', 'GroupC', 'GroupD')
'pc03' = #('GroupA', 'GroupB', 'GroupE')
'pc04' = #('GroupZ')
}
$NoGroupFound = '__No Group Found__'
$Results = foreach ($CL_Item in $ComputerList)
{
# use a real call to Get-ADComputer here [*grin*]
# pro'ly something like "(Get-ADComputer $CL_Item -Property MemberOf).MemberOf -join '; '"
$GroupList = $GroupMembershipLookup[$CL_Item] -join '; '
if ([string]::IsNullOrEmpty($GroupList))
{
$GroupList = $NoGroupFound
}
[PSCustomObject]#{
ComputerName = $CL_Item
GroupMembership = $GroupList
}
}
# on screen
$Results
# to CSV
$Results |
Export-Csv -LiteralPath "$env:TEMP\Del_GroupMembershipList.csv" -NoTypeInformation
on screen output ...
ComputerName GroupMembership
------------ ---------------
pc01 GroupA; GroupB
pc02 GroupB; GroupC; GroupD
pc03 GroupA; GroupB; GroupE
pc04 GroupZ
pc05 __No Group Found__
pc666 __No Group Found__
csv content ...
"ComputerName","GroupMembership"
"pc01","GroupA; GroupB"
"pc02","GroupB; GroupC; GroupD"
"pc03","GroupA; GroupB; GroupE"
"pc04","GroupZ"
"pc05","__No Group Found__"
"pc666","__No Group Found__"
what the above does ...
creates an array of system names as if they had been read in via Get-Content
creates a lookup table as if one had used Get-ADComputer to get the group membership for each system
made a "not found" value & stored that in a $Var for reuse
iterated thru the $ComputerList collection
grabbed the list/array of groups and converted them into a semicolon delimited string
tested for "no groups found" & added the value saved earlier if the list was empty
built a [PSCustoObject] and sent that to the output stream
captured the output stream to an array named $Results all at one time to avoid the += array penalty
displayed the results on screen
sent the $Results collection to a CSV file

Change email address in CSV

I am writing PowerShell code to export email addresses to a csv file and edit them. I've written the following:
# Script to get all DLs and email addresses in csv file
Get-ADGroup -Filter 'groupcategory -eq "distribution"' -Properties * |
select Name, mail |
Export-csv "C:\temp\Distribution-Group-Members.csv"
# Following will import the csv, make new column as proxy and save the file
# as update.csv
Import-Csv "C:\temp\Distribution-Group-Members.csv" |
Select-Object "Name", "mail", #{n = "proxy"; e = "mail"} |
Export-Csv "c:\temp\Distribution-Group-Members-Updated.csv" -NoTypeInfo
# Following script can import the csv and set proxy addresses from proxy
# column
Import-Csv "c:\temp\Distribution-Group-Members-Updated.csv" |
Foreach {
Get-ADGroup $_.Name | Set-ADGroup -Add #{
proxyaddresses = ($_.proxy -split ";")
}
}
Now, I would like to add 2 more features in the script:
update domain for existing mail column e.g. update mail address form test#abc.com to test#xyz.com
Add SMTP:test#xyz.com;smtp:test#abc.com" as Proxy mail address, so that xyz become primary mail address and abc as proxy domain
So assuming my DL name is "DL Test" email is "test#abc.com" => The script should update the email address of DL to "test#xyz.com" and add "smtp:test#abc.com" as proxy mail address
Can someone please advise, how can I achieve that?
The part where you have written:
select-object "Name", "mail", #{n = "proxy"; e = "mail"}|
The proxy part is called a calculated property. The first two with just names Name and Mail are copied directly from the input objects, but using the #{..} syntax, you can put code to calculate a new value instead.
So you can use this to achieve both your desired changes:
Import-Csv -Path 'C:\temp\Distribution-Group-Members.csv' |
Select-Object -Property Name,
#{Label='Mail'; Expression={$_.Mail -replace 'abc', 'xyz'}},
#{Label='Proxy'; Expression={"SMTP:$($_.Mail -replace 'abc', 'xyz');smtp:$($_.Mail)"}}|
Export-csv 'C:\temp\Distribution-Group-Members.csv' -NoTypeInformation