Im trying to set AD Title and Department based on a set of data and I can seem to get it to accept my userdetails says object is not set to an instance of an object.
Here is the code I am using:
$list = Import-Excel -Path "\\VRIDATA\HelpDesk\Scripts\Dan\Guardian.xlsx"
foreach($User in $list)
{
$display = $User.Name
$dept = $User.Department
$title = $User.JobTitle
$UserID = Get-ADUser -Filter { Name -like $display } | Select samAccountName
$Userdetails = #{
Identity = $UserID
Title = $title
Department = $dept
}
Set-AdUser #Userdetails
}
Related
I need to add new email aliases to the users in the specific OU, with a specific format like:
user Alias / sAMAccountName = First Lastname
newAlias = FLastname#NewBrandX.com
User with Apostrophe
user Alias / sAMAccountName = John O'Dea
newAlias = JOdea#NewBrandX.com
User with either First or Lastname with spaces
user Alias / sAMAccountName = Peter Van Denberg
newAlias = PVanDenberg#NewBrandX.com
However, my script skill is quite limited, so I wonder if anyone can assist in the script modification below:
$newproxy = "#NewBrandX.com"
$userou = 'OU=Users,OU=Seattle,DC=usa,DC=contoso,DC=com'
$paramGetADUser = #{
Filter = 'Enable -eq $true'
SearchBase = $userou
Properties = 'SamAccountName', 'ProxyAddresses', 'givenName', 'Surname'
}
$users = Get-ADUser #paramGetADUser
Foreach ($user in $users)
{
$FirstName = $user.givenName.ToLower() -replace '\s', ''
$LastName = $user.surname.ToLower() -replace '\s', '' -replace "'", ''
Set-ADUser -Identity $user.samaccountname -Add #{ proxyAddresses = "smtp:" + $FirstName + $LastName + $newproxy }
}
It looks to me like you want a create a new proxy address in format
First character of GivenName
Surname without apostrophes or spaces
followed by "#NewBrandX.com".
Your code however takes the full GivenName.
To add to the ProxyAddresses array, you need to replace the entire [string[]] array
$newproxy = "#NewBrandX.com"
$userou = 'OU=Users,OU=Seattle,DC=usa,DC=contoso,DC=com'
$paramGetADUser = #{
Filter = 'Enable -eq $true'
SearchBase = $userou
Properties = 'ProxyAddresses' # SamAccountName, GivenName and Surname are returned by default
}
$users = Get-ADUser #paramGetADUser
foreach ($user in $users) {
$newAddress = ("smtp:{0}{1}$newproxy" -f $user.GivenName.Trim()[0], ($user.Surname -replace "[\s']+").ToLower())
$proxies = #($user.ProxyAddresses)
# test if this user already has this address in its ProxyAddresses attribute
if ($proxies -contains $newAddress) {
Write-Host "User $($user.Name) already has '$newAddress' as proxy address"
}
else {
Write-Host "Setting new proxy address '$newAddress' to user $($user.Name)"
$proxies += $newAddress
# proxyAddresses needs a **strongly typed** string array, that is why we cast the $proxies array with [string[]]
$user | Set-ADUser -Replace #{ proxyAddresses = [string[]]$proxies }
}
}
im currently working on a automated User Attributes updating scrips, and currently that working fine, i am having issues however collecting the list of changes so they can be bundled inot an email notification for the administrator
here is what i have so far,
i want to form a list of all changes so that i can add that to an send-mailmessage to an admin for each user, but only when there is a change.
at the moment i only get whatever the latest thing changed is, not a list.
$csvFile = 'C:path.csv' # Enter a path to your import CSV file
$validUsernameFormat = '[^a-zA-Z_.]' # identifies anything that's _not_ a-z or underscore or .
$Mailpassword = ConvertTo-SecureString -string “4a1fd5e9f7e26f” -AsPlainText -Force
$MailCred = New-Object System.Management.Automation.PSCredential -argumentlist "38da1ca9daf082", $Mailpassword
$mailBody = $NewUserParams | out-string
# read the input csv and loop through
Import-Csv -Path $csvFile | ForEach-Object {
$firstName = $_.FirstName.Trim()
$surname = $_.Surname.Trim()
#$validUsernameFormat = "[^a-zA-Z_.]" # identifies anything that's _not_ a-z or underscore or .
$vaildusername = "($firstName'.'$surname)" -replace $validUsernameFormat, '' #removes anything that isn'tin $validUsernameFormat
$truncateifgreaterthanXchar = '(?<=^.{20}).*'
$username = $vaildusername -replace $truncateifgreaterthanXchar
$DefaultPassword = 'Pa$$w0rd'
$securePassword = ConvertTo-SecureString -String $DefaultPassword -AsPlainText -Force
# test if a user with that name already exists
$user = Get-ADUser -Filter "SamAccountName -eq '$username'" -ErrorAction SilentlyContinue
if ($user) {
$CurrentAttributes = Get-ADUser -Identity $username -Properties *
# You don't need this line because you are already declaring the variable in the next one
# [psobject]$CorrectAttributes
$CorrectAttributes = #{
SamAccountName = $username
Name = "$firstname $surname"
DisplayName = "$firstname $surname"
UserPrincipalName = "$username#domain.com"
GivenName = $firstname
Surname = $surname
Path = "CN=Users,DC=domain,DC=com" #change to switch based of Users Branch
City = $_.City
Country = $_.Country #NOTE: This Feild must be the 2 digit Country Code, NOT the String Name of athe Country.
department = $_.OrgDepartmentName
Employeeid = $_.EmployeeId
mobile = $_.Mobile
Manager = $_.Manager
Office = $_.Branch
postalCode = $_.PostalCode
POBox = $_.PostOfficeBox
scriptPath = $_.scriptPath
Street = $_.StreetName
Title = $_.Title
}
[System.Collections.ArrayList]$MailAttributesList = #()
foreach ($attribute in $CorrectAttributes.Keys) {
if ($currentAttributes.$attribute -ne $correctAttributes.$attribute) {
$params = #{Identity = $username; $attribute = $correctAttributes.$attribute }
$mailUpdatedAttribute = $CorrectAttributes.$attribute | Out-String
Set-ADUser #params
[void]$MailAttributesList.add("$attribute")
}
else {
Write-Host "$username '$attribute' is correct"
}
$MailAttributesList
$MailAttributesList = #()
}
}
Taken from the part where you test if the user exists and then check which attributes need to be updated, I'd do this:
# personally, I hate using -Properties *
# better to list the properties you are trying to update:
$userAttribs = 'SamAccountName','Name','DisplayName','UserPrincipalName',
'GivenName','Surname','Path','City','Country','Department',
'EmployeeId','MobilePhone','Manager','Office','PostalCode',
'POBox','ScriptPath','Street','Title'
# test if a user with that name already exists
$user = Get-ADUser -Filter "SamAccountName -eq '$username'" -Properties $userAttribs -ErrorAction SilentlyContinue
if ($user) {
# always https://learn.microsoft.com/en-us/powershell/module/addsadministration/set-aduser
# for the correct parameter names!
$CorrectAttributes = #{
SamAccountName = $username
Name = "$firstname $surname"
DisplayName = "$firstname $surname"
UserPrincipalName = "$username#domain.com"
GivenName = $firstname
Surname = $surname
Path = "CN=Users,DC=domain,DC=com" #change to switch based of Users Branch
City = $_.City
Country = $_.Country #NOTE: This Feild must be the 2 digit Country Code, NOT the String Name of athe Country.
Department = $_.OrgDepartmentName
EmployeeId = $_.EmployeeId
MobilePhone = $_.Mobile
Manager = $_.Manager # must be a DistinguishedName, GUID, SID or SamAccountName
Office = $_.Branch
PostalCode = $_.PostalCode
POBox = $_.PostOfficeBox
ScriptPath = $_.scriptPath
Street = $_.StreetName
Title = $_.Title
}
# create a new empty hashtable to store the properties that need updating
$UpdateAttribs = #{}
# capture all changes on behalf of the email body
$changes = foreach ($prop in $CorrectAttributes.Keys) {
if ($user.$prop -ne $CorrectAttributes[$prop]) {
# output an object with the property to be changed for the email
[PsCustomObject]#{
Property = $prop
OldValue = $user.$prop
NewValue = $CorrectAttributes[$prop]
}
# add the value to update in the the $UpdateAttribs hashtable
$UpdateAttribs[$prop] = $CorrectAttributes[$prop]
}
}
if ($changes) { # or do: if ($UpdateAttribs.Count)
# perform the changes
$user | Set-ADUser #UpdateAttribs
# send the email to the admin
$mailParams = #{
To = 'admin#yourcompany.com'
From = 'attributeChanger#yourcompany.com'
Subject = 'User attributes changed'
Body = "Changed AD attributes for user $username`r`n" + ($changes | Format-Table -AutoSize | Out-String)
SmtpServer = 'smtp.yourcompany.com'
UseSsl = $true
Credential = $MailCred
# maybe more parameters go here..
}
Send-MailMessage #mailParams
}
else {
Write-Host "All attributes for user '$username' are correct"
}
}
else {
Write-Warning "User $username does not exist"
}
P.S. The code could be shortened if you have your input CSV file use the correct headers, so they match the property names for Set-ADUser exactly..
I need to aggregate the results of 2 foreach so I can run a nice report - this is the script:
$users = Get-ADGroupMember -Identity 'TESTGRoup'
$result1 = ForEach ($user in $users){
New-Object -TypeName psobject -Property #{
User = $user
CN = $User.SamAccountName
Domain = $user.name
Name = $user.SID
}
}
$Result4 = Get-ADGroupMember 'TESTGRoup' |
Where-Object {$_.objectClass -eq 'User'} |
Get-AdUser |
ForEach {
Get-MsolUser -UserPrincipalName $_.UserPrincipalName | Select UserprincipalName, Blockcredential
$result7 = New-Object -TypeName psobject -Property #{
User1 = $Result4.UserPrincipalName
CN1 = $Result4.BlockCredential
}
}
The end result is all the users joined up on a single line and not on a table.
Sorry for the code format - not sure how to present it better.
Thanks
If I understand your question correctly, the below code will generate objects with the aggregated data you need on a single object per user:
#requires -Version 3
$results = foreach ($user in Get-ADGroupMember -Identity 'TESTGRoup')
{
$user | ? objectClass -eq User | Get-ADUser | % {
$msol = Get-MsolUser -UserPrincipalName $PSItem.UserPrincipalName
[pscustomobject]#{
'User' = $user
'CN' = $user.SamAccountName
'Domain' = $user.Name
'Name' = $user.SID
'User1' = $msol.UserPrincipalName
'CN1' = $msol.BlockCredential
}
}
}
Making a script at work to save some time getting approval from a Security Group owner when someone requests access to a group.
It works OK, but not great. The idea is to create a draft in Outlook2010 that is auto-filled with SG Manager Email address, Subject entered by Analyst. The body contains the requesting users Office, Dept, Manager, and Job title.
It does all this fine, but there is zero error catching, so for example, if the group name entered by the Analyst is wrong or annoyingly has a space at the end, it retains the information saved in the $managerEmail from last time you run it (I thought -like would sort this, but it does not).
Also, it only works for one user, one group, one email - where in reality there could be multiple users requesting access or a user requesting access to multiple groups. I'm looking for a hint in the right direction - would I need to employ a loop of some kind in it to accept multiple inputs and create multiple Email drafts?
It's a mash of bits of scripts together with my own extremely novice "code" so I'm sure there are parts that do nothing of value so any cleanup advise would also be appreciated, I'm not sensitive about it so any thoughts please share.
Get-Module -ListAvailable
Import-Module ActiveDirectory
#Below is user inputs required
$User = Read-Host -Prompt 'Input the user name'
$Group = Read-Host -Prompt 'Input Group Name'
$Notify = Read-Host -Prompt 'Input Notify Subject Line'
#Below is the user info
Get-ADUser -Filter {name -like $user}
if ($User -ne $null)
{
$Find = Get-ADUser $User -Server americas.cshare.net –Properties * |
Select-Object Office, Department, Name, Manager, Title
$Office = $Find.Office
$Dept = $Find.Department
$Title = $Find.Title
$Name = $Find.Name
$Usermanager = $Find.Manager
}
$UM = (get-aduser -Identity $Usermanager -Server americas.cshare.net -Properties Name);
$UserManagerName = $UM.Name;
#Below is get owner name and email need to add error catching
Get-ADGroup -Filter {name -like $Group} -Server americas.cshare.net -Properties ManagedBy |
ForEach-Object {
$managedBy = $_.ManagedBy;
if ($managedBy -ne $null)
{
$manager = (get-aduser -Identity $managedBy -Server americas.cshare.net -Properties emailAddress);
$managerName = $manager.Name;
$managerEmail = $manager.emailAddress;
}
else
{
$managerName = 'N/A';
$managerEmail = 'N/A';
}
Write-Output $_;
} |
Select-Object -Property #(
#{n = 'Group Name'; e = {$_.Name}}
#{n = 'Managed By Name'; e = {$managerName}}
#{n = 'Managed By Email'; e = {$managerEmail}}
)
#Below is the email part saves a draft to check yourself before sending
$ol = New-Object -comObject Outlook.Application
$mail = $ol.CreateItem(0)
$null = $Mail.Recipients.Add("$managerEmail")
$Mail.Subject = "$Notify"
$Mail.Body = #"
Dear $managerName,
$Name has requested to be added to the security group $Group
Job Role: $Title
Department: $Dept
Office: $Office
Manager: $UserManagerName
As the owner of $Group, can you review this request and approve/deny accordingly.
Please REPLY ALL when you respond.
Kind Regards,
Service Desk
"#
$Mail.Save()
So I took a stab at it and added validation steps, but you don't really have much cause for "error handling" exactly. Since this script depends on a lot of user input, I cleaned up that process. Also addressed your problem with group searches. The filter doesn't support -match, so I added proper wildcards on each end of the group name (to catch those various bits). Not sure what the Select-Object was for at the end of your pipeline, but that's in there, too, in the form of New-Object.
Import-Module -Name ActiveDirectory
#region User details
do {
$user = Read-Host -Prompt SID
$adArgs = #{
Identity = $user
Server = 'americas.cshare.net'
Properties = 'Office','Department','Name','Manager','Title'
ErrorAction = 'SilentlyContinue'
}
$user = Get-ADUser #adArgs
if (-not $user) {
'SID not found in Active Directory. Try again.'
}
} until ($user)
$userName = $user.Name
$userTitle = $user.Title
$userDept = $user.Department
$userOffice = $user.Office
$userManager = Get-ADUser -Identity $user.Manager -Server americas.cshare.net -Properties Name |
Select-Object -ExpandProperty Name
#endregion
#region Group details
do {
$group = Read-Host -Prompt Group
$adArgs = #{
Filter = "Name -like '*$group*'"
Server = 'americas.cshare.net'
Properties = 'ManagedBy'
ErrorAction = 'SilentlyContinue'
}
$adGroup = Get-ADGroup #adArgs
if (-not $adGroup) {
'Group not found in Active Directory. Try again.'
}
if ($adGroup.Count -gt 1) {
'Multiple groups found matching query. Try again.'
$adGroup = $null
}
} until ($adGroup)
try {
$adArgs = #{
Identity = $adGroup.ManagedBy
Server = 'americas.cshare.net'
Properties = 'emailAddress'
ErrorAction = 'Stop'
}
$groupManager = Get-ADUser #adArgs
} catch {
"Failed to retrieve '$group' manager! $_" # prints the AD error
Pause
Exit
}
$groupManagerName = $groupManager.Name
$groupManagerEmail = $groupManager.emailAddress
#endregion
$subject = Read-Host -Prompt Subject
New-Object -TypeName PSCustomObject -Property #{
'Group Name' = $group
'Managed By Name' = $groupManagerName
'Managed By Email' = $groupManagerEmail
}
#region Draft an email
$ol = New-Object -ComObject Outlook.Application
$mail = $ol.CreateItem(0)
$null = $mail.Recipients.Add($groupManagerEmail)
$mail.Subject = $subject
$mail.Body = #"
Dear $groupManagerName,
$userName has requested to be added to the security group $group
Job Role: $userTitle
Department: $userDept
Office: $userOffice
Manager: $userManager
As the owner of $group, can you review this request and approve/deny accordingly.
Please REPLY ALL when you respond.
Kind Regards,
Service Desk
"#
$mail.Save()
#endregion
Pause
I have script that get all members of security groups across domains and export to CSV file in this format: Name, username, security group. But I want to add another row for the domain so format will look like this: domain\username, name, security group.
I could get the DN but I am only interested in just domain\username. I search around in the internet and I couldn't find anything and I am not sure if this even possible
$objForest = [System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest() $DomainList = #($objForest.Domains | Select-Object Name) $Domains = $DomainList | foreach {$_.Name}
$Groups = Import-Csv C:\ad.csv
$Table = #()
$Record = #{ "Group Name" = "" "Name" = "" "Username" = "" }
Foreach ($Group in $Groups) {
$Arrayofmembers = Get-ADGroupMember -identity $Group.groupad
-recursive -Server $Domain | select name,samaccountname
foreach ($Member in $Arrayofmembers) {
$Record."Group Name" = $Group.ad
$Record."Name" = $Member.name
$Record."UserName" = $Member.samaccountname
$objRecord = New-Object PSObject -property $Record
$Table += $objrecord
}
}
$Table | export-csv "C:\SecurityGroups3.csv" -NoTypeInformation
As Bum mentioned, you can use a regex to get the DC and combine it with the username:
$username = 'Michael'
$distinguishedName = 'CN=Domain Admins,CN=Users,DC=Fabrikam,DC=com'
$dc = [regex]::Match($distinguishedName, 'DC=([^,|$]+)').Groups[1].Value
$domainuser = '{0}\{1}' -f $dc, $username
Output of $domainuser:
$domainuser
Fabrikam\Michael