Im trying to pull just the names in specific AD fields, however I keep getting: "#{(Property)=Data}" when I write-host
'''
$TargetUserName = "User.test"
$Firstname = Get-ADUser -identity $TargetUserName -properties GivenName | Select-object GivenName
$Lastname = Get-ADUser -identity $TargetUserName -properties Surname | Select-object SurName
Write-Host $Firstname
Write-Host $Lastname
'''
Result:
#{GivenName=user}
#{SurName=Test}
I want it to just display the data within the result, so it needs to look like:
Result Desired:
user
Test
Im newer at Powershell, so bear with me please
You do not need write-host to display values of a variable or object property. You can reference them directly:
$TargetUserName = "User.test"
$ADUser = Get-ADUser -identity $TargetUserName
$ADUser.GivenName
$ADUser.Surname
The Get-ADUser command automatically returns an ADUser object with a default list of properties. Surname and GivenName are included so there is no need to use the -Properties switch in this case. The ADUser object property values can be accessed by using the objectname.property or (Object Expression).property.
Related
I am very new to powershell, still trying to figure out how it works. I have so far written a short script to take details from a CSV and poulate properties in AD.
If I use the username i.e smithj it works fine but I can't get it to take a name like John Smith and find the account it is associated with. This is the same with the manager field, it will take the username but I cant get it to take a full name.
Any help or advice would be much appreciated.
Import-module ActiveDirectory
$List = Import-CSV "\\SharedServer\shared\MYCSV.csv" | % {
$User = $_.UserName
$ID = $_.EmployeeID
$EmployeeNumber = $_.EmployeeNumber
$Description = $_.Description
$Department = $_.Department
$Title = $_.Title
$AccountExpirationDate = $_.AccountExpire
$Manager = $_.Manager
Set-ADUser $User -employeeID $ID -EmployeeNumber $EmployeeNumber -Description $Description -Department $Department -Title $Title -Manager $Manager -AccountExpirationDate $AccountExpirationDate
}
Depending on what the CSV contains for UserName and Manager, the best would be to have the SamAccountName or DistinguishedName because these attributes are unique within the same domain.
UserPrincipalName or EmailAddress would also do nicely for targeting the correct user.
From your question however, I gather that the CSV has the users Name in there that should correspond to the Name property of an AD user.
In that case I agree with I.T Delinquent that you can use that in the Filter parameter for Get-ADUser and that is also what my example code below uses.
Then there is the question of how you have entered the date for the AccountExpirationDate in the CSV file..
This parameter wants a DateTime object, not a string, so you'll have to convert that before use.
Finally, I would suggest using Splatting for cmdlets like Set-ADUser that take a lot of parameters.
Something like this:
Import-CSV "\\SharedServer\shared\MYCSV.csv" | ForEach-Object {
$user = Get-ADUser -Filter "Name -eq '$($_.UserName)'" -ErrorAction SilentlyContinue
if (!$user) {
Write-Warning "User '$($_.UserName)' not found"
}
else {
# convert the date string from the CSV into a real DateTime object
# Since I cannot see the CSV, you may need to do this using [DateTime]::ParseExact()
$expireDate = Get-Date $_.AccountExpire
# create a Hashtable for the parameters
$userProps = #{
'EmployeeID' = $_.EmployeeID
'EmployeeNumber' = $_.EmployeeNumber
'Description' = $_.Description
'Department' = $_.Department
'Title' = $_.Title
'AccountExpirationDate' = $expireDate
}
# get the manager object from the name
$manager = Get-ADUser -Filter "Name -eq '$($_.Manager)'" -ErrorAction SilentlyContinue
if ($manager) {
$userProps['Manager'] = $manager.DistinguishedName
}
$user | Set-ADUser #userProps
}
}
When using UserPrincipalName or EmailAddress, change the Filter into "UserPrincipalName -eq '$($_.UserName)'" or "EmailAddress -eq '$($_.UserName)'".
You might even want to experiment with Ambiguous Name Resolution..
I would use Get-ADUser and then pipe the object that was returned into Set-ADUser. Here is a quick example:
Get-ADUser -Filter " Name -eq 'Name here' " | Set-ADUser -employeeID $ID
I'm trying to create a script for remote deletion of local profiles across the network.
I am using delprof2 as the program and I have got it set to the computers network name but when trying to specify the username to look for and delete, the script returns the full DistinguishedName including the OU and Dc etc. All I need it to return is the SamAccountName contents without the CN= infront.
Can anyone help?
I've tried a -filter instead of -ldapfilter.
I've changed the samaccount name in the brackets to $name.samaccountname= and even CN=.
function CheckUser{
$user = Get-ADUser -LDAPFilter "(samaccountname=$user)"
If ($user -eq $Null)
{"User does not exist in AD";GetUserName}
Else {GetMenu}
The required outcome is for the $user variable to hold the SamAccountName data only.
Get-ADUser returns the property SamAccountName by default, aswell as DistinguishedName, Enabled, GivenName, Name, ObjectClass, ObjectGUID, SID, Surname and UserPrincipalName.
The Get-ADUser cmdlet can take the following entries for its -Identity parameter:
DistinguishedName
GUID
SID
SamAccountName
and if like your question suggests you already have the DistinghuishedName or SamAccountName to check on, you can simply use that for the Identity parameter and not use the Filter at all.
Something like this should work:
function CheckUser {
[CmdletBinding()]
param(
[Parameter(ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, Position = 0)]
[string]$UserToCheck # can be DistinghuishedName, GUID, SID or SamAccountName
)
$user = Get-ADUser -Identity $UserToCheck
if (!$user) {
"User does not exist in AD"
}
else {
# return the SamAccountName of the user
return $user.SamAccountName
}
}
Use this like
$samaccountname = CheckUser -UserToCheck 'the property you have, like the DistinghuishedName'
If you have some other property of the user you need to use, like email address, then you DO need to use the filter (or LDAPFilter) to search for the user.
Something like
$user = Get-ADUser -Properties EmailAddress -Filter "EmailAddress -eq '$UserToCheck'"
or
$user = Get-ADUser -LDAPFilter "(mail=$UserToCheck)"
Hope this helps
Thanks for everyones help
after trying what everyone suggested I changed the script around in its original form and in context this now works
function CheckUser{
Get-ADUser -LDAPFilter ("samaccountname=$user") = $user
If ($user -eq $Null)
{"User does not exist in AD";GetUserName}
Else {GetMenu}
}
as you can see this is now setting the samaccountname as the $user
I put a test in using a menu function
4 {#Show Stored Username
Read-host $user
CheckUser
}
and the output is the correct username
This now passes the correct variable to DelProf2.exe for remote profile deletion.
I want to make a script that deletes bulk users, instead of using SAMACCOUNTNAME I want to use the first and last name, is that possible?
Import-Module ActiveDirectory
$ADusers = Import-csv C:\TEST\Delete.CSV
Foreach ($user in $ADusers) {
#Confirming the identity
$users = Get-ADUser -Identity $user -Properties | Select-Object Givenname, Surename
#Removing the user
Remove-ADUser -Identity $user.samAccountName -Confirm:$false
}
I like Ambiguous Name Resolution when searching for users in AD:
Get-ADUser -LDAPFilter "(anr=Jim Smith)"
This will search for all objects where any of the naming attributes (see link above for list) start with the string "jim smith", plus all objects where (givenName=jim*) and (sn=smith*), plus objects where (givenName=smith*) and (sn=jim*).
This is useful when 'Jims' account uses his fully name of 'Jimmy', this would be returned by ANR but not by a direct givenName/sn filter.
You can have multiple users with the same First/Last name, so you will need to deal with the situation of multiple users being returned.
SAMAccoutName, however is unique to a single account
EDIT:
If you've got a csv with the two columns GivenName & Surname:
foreach ($user in $ADusers) {
$firstname = $user.GivenName
$lastname = $user.Surname
Get-ADUser -LDAPFilter "(anr=$firstname $lastname)"
}
The above just lists the users returned from Get-ADUser, to remove them just pipe to Remove-ADUser. I'm using WhatIf to test, remove to actually delete the users:
Get-ADUser -LDAPFilter "(anr=$firstname $lastname)" | Remove-ADUser -WhatIf
Yes it is.
Get-ADUser -Filter {GivenName -eq "Max" -and sn -eq "Muller"} | Remove-ADUser
You need to alter your script accordingly.
Can someone please tell me how I can rename sn and givenName of a contact object in active directory?
This is how I query the data in my contacts OU:
Get-ADObject -Filter {(ObjectClass -eq "contact") -and (givenName -like "*myName*") } -Properties sn, givenName -SearchBase "OU=contacts,DC=domain,DC=name"
From Microsoft:
To modify the given name, surname and other name of a user, use the
Set-ADUser cmdlet
My goal is to modify the values of both properties because I have text that is all in lowercase and I was hoping to use something like:
$TextInfo = (Get-Culture).TextInfo
$TextInfo.ToTitleCase("one-two three")
Desired Output: One-Two Three
to get a capital letter for each word.
Some examples would be great.
If you know of a GUI-Tool that does what I need then please share as well.
To change the attributes on a contact AD object you will need to use the Set-ADOject Cmdlet, with the -Replace parameter. Set-ADUser will only set attributes of an AD object of type user.
The following code will take the full name of the contact object, search for it in AD and then change the GivenName, SN and DisplayName to title case.
I have added the DisplayName as this field is not automatically update when you change the first and last name, but you can delete this part if it's not needed.
$fullname = "My Name"
$contact = Get-ADObject -Filter {(ObjectClass -eq "contact") -and (Name -like $fullname)} -Properties * -SearchBase "OU=contacts,DC=domain,DC=name"
$TextInfo = (Get-Culture).TextInfo
$GivenNametoTitleCase = $TextInfo.ToTitleCase(($contact.givenName).ToLower())
$SNtoTitleCase = $TextInfo.ToTitleCase(($contact.sn).ToLower())
$DisplayNametoTitleCase = $TextInfo.ToTitleCase(($contact.DisplayName).ToLower())
$contact | Set-ADObject -Replace #{GivenName=$GivenNametoTitleCase;`
sn=$SNtoTitleCase;`
DisplayName=$DisplayNametoTitleCase;}
I am trying to figure out how to grab a userID's last name attribute but not sure how. I have tried to look at some examples but are falling short. Below is what I have so far but want to either get the last name attribute separately or grab the display name (which is first.last) and pull all the information after the period. Please help
Import-Module activedirectory
#$userID = Get-Aduser -filter *
$userIDs = Get-Aduser "w35522"
foreach ($lastName in $userIDs) {
$lastname = (get-Aduser -Filter * -Properties displayname).lastname
}
write-host $lastName
Update:
Thanks to comment below I changed lastname to surname. Only issue is now it prints the OU too which I don't want.
Import-Module activedirectory
#$userID = Get-Aduser -filter *
$userIDs = Get-Aduser "w35522"
foreach ($user in $userIDs) {
$lastname = get-Aduser -Identity $userIDs -Properties * | Select-Object name, GivenName, SurName, DisplayName
$user.SurName
write-host $user
}
prints:
Weyers
CN=w35522,OU=Standard,OU=Users,OU=Corporate,DC=we,DC=dirsrv,DC=com
FINAL UPDATE:
ok figured it out. It needed to say write-host $lastname instead!
thanks
The property which is returned by default that you are looking for is surname. That being said you have other logic issues in your script.
Get-ADUser someuser| select surname
Once in the loop you do another Get-Aduser. Also you assign a value to $lastName which is the pipe object you should be attempting to access.
If you really wanted all the lastnames in the company you would do something like this.
Get-ADUser -Filter * | Select-Object Surname