Powershell Assign MobilePhone property from Active Directory to variable - powershell

I have a small script I wrote but I am wondering if this is the correct way to pull the MobilePhone property from Active Directory using powershell?
$csvfi = import-csv "C:\Users\\Documents\users.csv"
foreach($row in $csvfi)
{
$cellphone = $row.Phone
$fullname = $row.Name
$adphone = (Get-ADUser -Filter "Name -eq '$fullname'" -Properties * | Select MobilePhone).MobilePhone
Write-Host $fullname, $adphone
}
It just seems cumbersome to do -Filter, then -Properties *, then pipe to Select and then get the .MobilePhone attribute from that object.
As a side note, I just need the raw Mobile Phone number from AD, 1-AAA-NNN-NNNN so I can compare it with the cell phone number in the spread sheet users.csv.

$adphone = (Get-ADUser -Filter "Name -eq '$fullname'" -Properties MobilePhone).MobilePhone

Related

Powershell GUI How can I add column to GridView

This is part of a much larger script 1443 lines to be exact. it pulls the username from AD based on first and last name. I need to also have it pull the Office name from AD to help better identify users with same name. I am sure I am just missing something simple.
function getacctname {
$fname = $FirstName.Text
$lname = $LastName.Text
Try {
$User.Text = Get-ADUser -Filter "GivenName -eq '$fname' -and SurName -eq '$lname'" |
Select-Object -ExpandProperty 'SamAccountName' |
Out-Gridview -Title 'Windows Logon' -PassThru
$Email.Text = (Get-ADUser $User.text -Properties mail).mail
}
Out-GridView dynamically builds its columns based on the input data you feed to it - so in order to get 3 columns, create an object with 3 properties!
Change the Select-Object statement so that it creates an object with properties corresponding to your desired columns and Out-GridView takes care of the rest:
Get-ADUser -Filter "GivenName -eq '$fname' -and SurName -eq '$lname'" -Properties physicalDeliveryOfficeName |
Select-Object 'SamAccountName',#{Name='Office';Expression={$_.physicalDeliveryOfficeName}} |
Out-Gridview -Title 'Windows Logon' -PassThru
If the office name is stored in a different attribute, replace the two occurrances of physicalDeliveryOfficeName with the ldap display name of the attribute in question

Need to update missing employee IDs in Active Directory by matching on Name in flat file

Recently completed an Azure AD provisioning integration between SuccessFactors and On-Prem AD.
In order for some of our existing users to get 'scoped in' to the Update provisioning, they first need to match on employee id (we currently do not use the Create functionality).
There are about 400 users that we've identified need to be matched, and our HR team has provided us with a csv with the following attributes (Full Name, EmployeeID). I need to somehow compare this file with all users in AD who have no employee id, and if not, update EmployeeId with the contents from the HR provided file.
I'm a bit stuck on how to attack this. Need a Big Brain :)
#import HR file with required attributes "Formal Name, EmployeeId"
#returns ~6500 entries
$SFUsers = Import-Csv Z:\ExportsFromProd\Global_ActiveHeadcountReport_08292022.csv
#returns ~1400 entries
#some accounts never get an employee id
$users = Get-ADUser -Filter "*" -Properties EmployeeID | Where-Object {$_.employeeID -eq $null}
foreach ($account in $users) {
$accountName = $account.name
get-aduser -Filter {Name -eq $accountName} -Properties * | Select-Object samaccountname, displayName
#this is where i need help:
<#
try {
Lookup $SFUser.'Formal Name' in $SFUsers array???
Get $SFUser.'EmployeeID' | set-aduser $account -employeeId $SFUser.'EmployeeId'
}
catch {
}
finally {
}
#>
}
'''
You can use the faster -Filter or LDAPFilter parameters of Get-ADUser to find only users where the EmployeeID property is unset.
Also, your code could be done by using Get-ADUser only once:
#import HR file with required attributes "Formal Name, EmployeeId"
#returns ~6500 entries
$SFUsers = Import-Csv -Path 'Z:\ExportsFromProd\Global_ActiveHeadcountReport_08292022.csv'
#returns ~1400 entries
#some accounts never get an employee id
$users = Get-ADUser -Filter "employeeid -notlike '*'" -Properties DisplayName, EmployeeID
# or use LDAPFilter
# $users = Get-ADUser -LDAPFilter "(!employeeID=*)" -Properties DisplayName, EmployeeID
foreach ($account in $users) {
# try and find this user in the csv file either by .Name or .DisplayName property
$HRUser = $SFUsers | Where-Object { $_.'Formal Name' -eq $account.Name -or
$_.'Formal Name' -eq $account.DisplayName}
if ($HRUser) {
$account | Set-ADUser -EmployeeID $HRUser.EmployeeId
}
else {
Write-Warning "AD user $($account.Name) not found in the CSV file.."
}
}

Why am I using too much disk space with this code?

I'm trying to extract some readable variables from AD, the following works.
$user = get-aduser "username" -Properties memberof, emailAddress, extensionattribute2, manager, physicalDeliveryOfficeName, url
$groups = ForEach ($group in $user.memberof){(Get-ADGroup $group).Name}
$groupStr = $groups -join "; " #Change "; " to "`r`n" for line break seperator
$user | Select-Object `
#{N="firstName";E={$_.GivenName}}, `
#{N="lastName";E={$_.Surname}}, `
#{N="email";E={$_.EmailAddress}}, `
#{N="businessArea";E={$_.extensionattribute2}}, `
#{N="accountName";E={$_.SamAccountName}}, `
#{N="manager";E={$_.Manager -replace '^CN=|,.*$'}}, `
#{N="office";E={$_.physicalDeliveryOfficeName}}, `
#{N="standardProfile";E={$_.url}}, `
#{n='Groups'; e={$groupStr}} | Export-CSV -NoTypeInformation "c:\out.csv"
However when I swap Get-aduser "username" to: Get-aduser -Filter {Enabled -eq $true} -SearchBase “ou=redacted,ou=UserAccounts,dc=redacted,dc=com”
It runs for a fairly long time and fills up the last 40gb on the disk and errors out as it's run out of space.
I know in the past I've wildcarded -Properties and run into similar issues (obvious now I understand) but I'm not sure what's causing the issue this time round.
{Enabled -eq $true} & -SearchBaselimit it to about 4 thousand users which I wouldn't think would take this long to run, and I've no idea what's using up the disk space.
Thanks in advance!
A slight augment in your code can achieve the results you want:
$users = get-aduser -filter "Enabled -eq '$true'" -Properties memberof, emailAddress, extensionattribute2, manager, physicalDeliveryOfficeName, url
$users | Foreach-Object {
$groups = ForEach ($group in $_.memberof) {
(Get-ADGroup $group).Name
}
$groupStr = $groups -join "; " #Change "; " to "`r`n" for line break separator
$_ | Select-Object #{N="firstName";E={$_.GivenName}},
#{N="lastName";E={$_.Surname}},
#{N="email";E={$_.EmailAddress}},
#{N="businessArea";E={$_.extensionattribute2}},
#{N="accountName";E={$_.SamAccountName}},
#{N="manager";E={$_.Manager -replace '^CN=|,.*$'}},
#{N="office";E={$_.physicalDeliveryOfficeName}},
#{N="standardProfile";E={$_.url}},
#{n='Groups'; e={$groupStr}}
} | Export-CSV -NoTypeInformation "c:\out.csv"
In your original code, $groups contains all of the groups for all enabled AD Users if you don't pick a specific user object for get-aduser. This is because $user.memberof will return all groups for every user in the $user array. Imagine 10 groups per user at 5000 users. You would have 50000 groups per user in your CSV.
-Properties adds attributes to return from the objects you are querying. It does not impact the number of objects you return only the size of the returned result. -Properties * vs. -Properties Attribute1,Attribute2 will likely use more memory but won't impact your CSV since you are selecting (Select-Object) the attributes you want to output. If you run Get-ADUser username, it will return a default list of attributes, which does not include mail for example. If you want to see the mail value along with the default attributes, then you must run Get-ADUser username -Properties Mail.

Powershell AD lookup by name and samaccountname variables

Two questions, first one is probably quite simple but it's extremely annoying. I'm running a script for AD lookup with the user name variable as an attribute:
[string]$FirstName = Read-Host "User First Name"
[string]$LastName = Read-Host "User Last Name"
[string]$FullName = "*$FirstName* *$LastName*"
write-host
Get-ADUser -Filter {name -like $FullName} -properties * | select-object name, samaccountname | sort-object
read-host "Press Enter to exit"
The problem is that "read host" is interpret as a part of the same command, and the query results appear after the prompt. I'd like to pause the script so the results can be read from the screen before console closes by hitting Enter. I've been experimenting with the brackets or different kind of loops but haven't been able to figure out how this should be done.
My second question is that I want to have samaccountname as a search attribute. Something like this:
[string]$Login = Read-Host "User Login name"
[string]$LoginName = "*$Login*"
The variable should be added to filter similar way the FullName variable is used.
1.)
A better way to pause the script and only continue after input, is to use:
$host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") > $null
The Query should come after the display of the Get-ADUser, if it still isn't working maybe submit some output examples or try getting the AD-User from Get-ADUser * | Where-Object {$_.Fullname like $Fullname}
2.)I'm not fully understanding your problem here, but if you want to get and User by his login name you can do it like this:
$login = Read-Host "Login name"
Get-ADUser $login | select-object name, samaccountname | sort-object
I managed to fix this myself. For the first question, adding "format-table" to the end of the pipeline closed the command and the script proceeded normally after that.
For the second question, as a workaround I just broke down the query as two separate ones. First one is searching for the full name, and the second one is searching for the login name:
Get-ADUser -Filter {name -like $FullName} -properties * | select-object name, samaccountname | sort-object name | format-table
write-host
Get-ADUser -Filter {samaccountname -like $LoginName} -properties * | select-object name, samaccountname | sort-object name | format-table
Good for you finding a solution to your problem,
I will put here also what I did and maybe you can use it.
First of all the first part:
$FirstName = Read-Host "Please provide the Fist name of the User: "
$LastName = Read-Host "Please provide the Last name of the User: "
$Fullname = "$FirstName $LastName"
$Users= Get-AdUser -Filter {name -like $FullName} -Properties * | Select Name, Samaccountname | Sort-Object -Verbose
Get-AdUser -Filter {name -like $FullName} -Properties * | Select Name, Samaccountname | Sort-Object -Verbose
#$Users
you can uncomment the last user variable to get the results on your screen.
as of your second question you can use the -or so you can search with the $fullname or the $login
$Login = Read-Host "User Login name"
Get-ADUser -Filter {name -like $FullName -or samaccountname -like $Login } -properties *
I would prefer a selection before running the code as I do with my checks on the AD
if you want to send you the code I can do it, I just don't want to put in this answer something different from what you ask.

How to add the value in input file as a column in exported output file in powershell?

I have a input file(input.txt) with the following data. The below data are saved in my domain as contacts. My task is to identify the corresponding mail id in my domain for these contacts.
abcd#otherdomain.com
efgh#otherdomain.com
ijkl#otherdomain.com
Below is the powershell script I wrote to accomplish the task. The targetaddress of these contacts will be my domain email id. But the problem here is, while exporting I need the input data also to be appended to my result.
Write-Host "Reading Input File.. "
$users=""
ForEach ($contact in $(Get-Content 'Input.txt'))
{
$DomainId = Get-ADObject -Filter {(mail -eq $contact) -and (ObjectClass -eq "Contact")} -Properties * | Select targetAddress
$DomainId = $DomainId.targetAddress.remove(0,5)
$users+= (Get-AdUser -Filter {Mail -eq $DomainId} -Properties * | Select Mail)
}
Write-Host "Exporting to CSV.."
$users | Export-CSV -Path 'output.csv' -NoTypeInformation
Below is the current output (output.csv)
Mail;
ab#mydomain.com;
ef#mydomain.com;
ij#mydomain.com;
But the expected output is,
Mail;InputId;
ab#mydomain.com;abcd#otherdomain.com;
ef#mydomain.com;efgh#otherdomain.com;
ij#mydomain.com;ijkl#otherdomain.com;
Is there a possibility to get the expected output. If so, please assist. Many thanks in advance for your support.
Untested, but something like this could work:
Write-Host "Reading Input File.. "
$users = foreach ($contact in (Get-Content 'Input.txt'))
{
$DomainId = Get-ADObject -Filter {
(mail -eq $contact) -and (ObjectClass -eq "Contact")
} -Properties * | Select-Object -ExpandProperty targetAddress
$DomainId = $DomainId.Remove(0,5)
$Mail = (Get-AdUser -Filter {Mail -eq $DomainId} -Properties Mail).Mail
[PSCustomObject]#{
InputId = $DomainId
Mail = $Mail
}
}
Write-Host "Exporting to CSV.."
$users | Export-CSV -Path 'output.csv' -NoTypeInformation
You want PSCustomObjects going into Export-CSV, with one property per column. And they are easy to build by casting from a hashtable, instead of using a lot of Add-Member.