Import-CSV "C:\Temp\jacktest.csv" | Foreach-Object {
$aduser = Get-ADUser -Filter "UPN-eq '$($_.UPN)'"
if( $aduser ) {
Write-Output "Adding user $($aduser.SamAccountName) to groupname"
Add-ADGroupMember -Identity JackTest -Members $aduser
} else {
Write-Warning "Could not find user in AD with email address $($_.EmailAddress)"
}
}
I receive the following Error:
Transcript started, output file is C:\Temp\Add-ADUsers.log
Get-ADUser : The search filter cannot be recognized
At line:19 char:15
$ADUser = Get-ADUser -Filter "UPN -eq '$UPN'" | Select-Object Sam ...
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CategoryInfo : NotSpecified: (:) [Get-ADUser], ADException
FullyQualifiedErrorId : ActiveDirectoryServer:8254,Microsoft.ActiveDirectory.Management.Commands.GetADUser
This answer is meant to help you troubleshoot your issue so we can understand what could be going wrong with your CSV.
Note, this code assumes that your CSV is comma delimited and the CSV has a column with name "UserPrincipalName".
$usersToAdd = foreach($line in Import-CSV "C:\Temp\jacktest.csv")
{
if([string]::IsNullOrWhiteSpace($line.UserPrincipalName))
{
Write-Warning 'Empty UserPrincialName Value:'
Write-Warning $line
continue
}
$aduser = Get-ADUser -Filter "UserPrincipalName -eq '$($line.UserPrincipalName)'"
if(-not $aduser)
{
Write-Warning "$($line.UserPrincipalName) could not be found."
continue
}
$aduser
}
if($usersToAdd)
{
Write-Host 'The following users will be added to the Group'
$usersToAdd.UserPrincialName
try
{
Add-ADGroupMember -Identity JackTest -Members $usersToAdd
}
catch
{
Write-Warning $_.Exception.Message
}
}
check the csv file, it seems you are not using the default delimiter.
if so add parameter -delimiter to the import-csv cmdlet.
for example for Tab delimiter:
Import-CSV "C:\Temp\jacktest.csv" -delimiter "`t"
Related
I have a problem importing phone numbers from a CSV file based on email addresses to Active directory using a PowerShell script.
The table contains:
mail;telephoneNumber
toto#domaine.com;88888888
tata#domaine.com;99999999
here’s the code I’m running but it shows me an error message, or I don’t see why there’s this message:
Import-module ActiveDirectory
Import-CSV E: scripts list.csv |
ForEach-Object {
Write-Host "telephoneNumber $($_.telephoneNumber)"
Get-ADUser -Filter "mail -like '$($_.mail)'" |
Set-ADUser -telephoneNumber $_. telephoneNumber}
Here is the error message:
telephoneNumber
Set-ADUser: Unable to find a parameter corresponding to the name «telephoneNumber».
Character E: scripts employeeid.ps1:6: 14
+ Set-ADUser -telephoneNumber $_. telephoneNumber}
+ ~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Set-ADUser], ParameterBindingException
+ FullyQualifiedErrorId: NamedParameterNotFound,Microsoft.ActiveDirectory.Management.Commands.SetADUser
NB: I am a beginner in the subject
Thank you well in advance for your help
I tried this code too but still the same problem.
Import-module ActiveDirectory
Import-CSV "E:\scripts\liste.csv" | % {
$telephoneNumber = $_.telephoneNumber
$mail= $ail_.m
Set-ADUser $telephoneNumber -mail $mail
}
The LDAP property telephoneNumber is known as OfficePhone in PowerShell and LDAP property mail has a PowerShell equivalent called EmailAddress.
Cmdlet Set-ADUser does not have a parameter called telephoneNumber, but it does have OfficePhone, so a rewrite of your code would be
Import-Module ActiveDirectory
Import-Csv -Path 'E:\scripts\list.csv' | ForEach-Object {
$user = Get-ADUser -Filter "mail -eq '$($_.mail)'" # or use PS equivalent 'EmailAddress'
if ($user) {
Write-Host "Setting telephoneNumber $($_.telephoneNumber) for $($user.Name)"
$user | Set-ADUser -OfficePhone $_.telephoneNumber
# if you do want to use LDAP property telephoneNumber, you can use below
# $user | Set-ADUser -replace #{telephoneNumber = $($_.telephoneNumber)}
}
else {
Write-Warning "Could not find user with EmailAddress $($_.mail)"
}
}
P.S. you made some typos when posting:
E: scripts list.csv is missing the backslashes
$_. telephoneNumber has a space between the dot and the property name
I have a .csv file that I am using to modify custom attributes on users in Active Directory, but PowerShell does not like the script:
Import-Csv -path c:\users\user\desktop\doc.csv | ForEach-Object {
Set-ADUser $_.mail -replace #{
ExtensionAttribute1 = $_.ExtensionAttribute1
}
}
I get the following error:
Set-ADUser : replace
At line:2 char:4
Set-ADUser $_.mail -replace #{
CategoryInfo: InvalidOperation: (user123:ADUser) [Set-ADUser], ADInvalidOperationException
FullyQualifiedErrorId: ActiveDirectoryServer:0,Microsoft.ActiveDirectory.Management.Commands.SetADUser
The CSV only has 2 columns:
extensionAttribute1,mail
Any help would be appreciated
The -Identity parameter for Set-ADUser does not take an email address.
It needs either the DistinguishedName, objectGUID, SID or SamAccountName. You can also pipe a user object directly to the cmdlet.
Because of that, you need to first try to find the user with Get-ADUser and if that succeeds set the attribute.
Import-Csv -Path 'c:\users\user\desktop\doc.csv' | ForEach-Object {
$user = Get-ADUser -Filter "EmailAddress -eq '$($_.mail)'" -ErrorAction SilentlyContinue
if ($user) {
$user | Set-ADUser -Replace #{ extensionAttribute1 = $_.extensionAttribute1 }
}
else {
Write-Warning "No user with email address '$($_.mail)' found.."
}
}
PS. I always use the exact LDAP name inside the Hash for the key name when using -Add, -Replace etc. Case sensitive.
I inherited several PowerShell scripts, to place a user on LitigationHold in Exchange, as well as set the user's AD protect from accidental deletion to $true.
They all work separately, but one uses User Full name, and the other uses the SAM account name. I am trying to marry scripts so that I can just use the Full name, but I can't seem to pass the SAMAccountName .
My attempt at combining the codes:
foreach ($user in ("Name 1", "Name 2", "Name 3"))
{
$mailuser = Get-Mailbox $user -DomainController A1.Domain l -ErrorAction SilentlyContinue| Select *;
if ($mailuser -eq $null)
{
Write-Host "$user was not found. Check for misspellings."
}
else
{
if($mailuser.LitigationHoldDate -ne $null)
{
Set-Mailbox $user -LitigationHoldEnabled:$true -Confirm:$False -Force:$True -DomainController A1.Domain;
Write-Host "$user is now placed on hold.";
$userinfo = {
Get-ADUser $user -Server A1.Domain
};
Set-ADObject -Identity $userinfo.SamAccountName -ProtectedFromAccidentalDeletion:$true;
$i = Get-ADUser $user -Properties description -Server A1.Domain |
%{ $_.description } |
Set-ADUser $userinfo -Server A1.Domain -Replace #{
description="8/19/2019 - Security Hold, please contact admin before modifying `r`n | $($i)"
}
}
else{
Write-Host "$user is already on litigation hold as of $($mailuser.LitigationHoldDate) by $($mailuser.LitigationHoldOwner)."
}
}
}
To take list of Display names and get usernames:
foreach ($user in ("Name 1", "Name 2", "Name 3"))
{
$userinfo = Get-ADUser -filter { DisplayName -like $user } -Server A1.Domain ;
if ($userinfo -ne $null)
{
Get-ADUser -filter { DisplayName -like $user } -Server A1.Domain | ft SamAccountName -HideTableHeaders
}
else
{
Write-Host "$user is not available"
}
}
To Add Lit Hold into AD Description
foreach ($user in ("Name 1", "Name 2", "Name 3"))
{
$mailuser = Get-Mailbox $user -DomainController A1.Domain -ErrorAction SilentlyContinue| Select *;
if($mailuser -eq $null)
{
Write-Host "$user was not found. Check for misspellings."
}
else
{
if ($mailuser.LitigationHoldDate -eq $null)
{
$i = Get-ADUser $user -Properties description -Server A1.Domain | %{ $_.description};
Set-ADUser $user -Server A1.Domain -Replace #{
description="Security Hold, please contact the Gnome before modifying `r`n | $($i)"
}
}
else
{
Write-Host "$user is already on litigation hold as of $($mailuser.LitigationHoldDate) by $($mailuser.LitigationHoldOwner)."
}
}
}
To take a list of Display names and set Lit Hold:
foreach ($user in ("Name 1", "Name 2", "Name 3""))
{
$mailuser = Get-Mailbox $user -DomainController A1.Domain -ErrorAction SilentlyContinue| Select *;
if ($mailuser -eq $null)
{
Write-Host "$user was not found. Check for misspellings."
}
else
{
if($mailuser.LitigationHoldDate -eq $null)
{
Set-Mailbox $user -LitigationHoldEnabled:$true -Confirm:$False -Force:$True -DomainController A1.Domain ;
Write-Host "$user is now placed on hold."
}
else
{
Write-Host "$user is already on litigation hold as of $($mailuser.LitigationHoldDate) by $($mailuser.LitigationHoldOwner)."
}
}
}
To take a list of usernames and protect against accidental deletion:
"User1", "User2", "User3" | Get-aduser -Server A1.Domain | Set-ADObject -ProtectedFromAccidentalDeletion:$true
I want to account to be set to LitigationHold, AD protect from accidental deletion, also reflect security hold on description.
This is the error message I get when I run it:
FN LN is now placed on hold.
Set-ADObject : Cannot validate argument on parameter 'Identity'. The argument is null. Provide a valid value for the argument, and then try running the
command again.
At line:9 char:25
+ Set-ADObject -Identity $userinfo.SamAccountName -ProtectedFromAccide ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Set-ADObject], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.ActiveDirectory.Management.Commands.SetADObject
Set-ADUser : A positional parameter cannot be found that accepts argument 'Get-ADUser $user -Server A1.domain '.
At line:12 char:1
+ Set-ADUser $userinfo -Server A1.domain -Replace # ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Set-ADUser], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.ActiveDirectory.Management.Commands.SetADUser
I was trying to see if I can bypass the -Identify flag by giving it the user full name, but Set-ADObject will only take an object, not a string.
--edit 3--
Replying to #Seth about -Identity flag is a parameter:
changed part of the code to give -Identity an ADObject:
$userinfo = Get-ADUser {DisplayName -like $user} -Server A1.domain};
Set-ADObject $userinfo -ProtectedFromAccidentalDeletion:$true;
The error message is as follows:
Get-ADUser : Cannot evaluate parameter 'Identity' because its argument is specified as a script block and there is no input. A script block cannot be
evaluated without input.
At line:8 char:26
+ $userinfo = Get-ADUser {DisplayName -like $user} -Server A1.domain ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : MetadataError: (:) [Get-ADUser], ParameterBindingException
+ FullyQualifiedErrorId : ScriptBlockArgumentNoInput,Microsoft.ActiveDirectory.Management.Commands.GetADUser
Set-ADObject : Cannot evaluate parameter 'Identity' because its argument is specified as a script block and there is no input. A script block cannot be
evaluated without input.
At line:9 char:15
+ Set-ADObject $userinfo -ProtectedFromAccidentalDeletion:$true;
+ ~~~~~~~~~
+ CategoryInfo : MetadataError: (:) [Set-ADObject], ParameterBindingException
+ FullyQualifiedErrorId : ScriptBlockArgumentNoInput,Microsoft.ActiveDirectory.Management.Commands.SetADObject
Set-ADUser : A positional parameter cannot be found that accepts argument 'Get-ADUser {DisplayName -like $user} -Server A1.domain'.
At line:12 char:1
+ Set-ADUser $userinfo -Server A1.domain -Replace # ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Set-ADUser], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.ActiveDirectory.Management.Commands.SetADUser
I think at this point the issue boils down to: Set-ADUser uses SamAccountName, and I can't seem to parse out the SamAccountName from the user ADObject. I can get the SamAccountName by calling a table from the ADObject, but it will not pass into Set-ADUser correctly.
You're currently not doing any verification on whenever you actually get a proper ADUser object. You simply assume that the assignment to $i/$userinfo will be successful. Your $name contains the display name for a user. So for example it would be "John Doe".
This works for Get-Mailbox because it supports Name, Alias, Distinguished name (DN), Canonical DN, <domain name>\<account name>, Email address, GUID, LegacyExchangeDN, SamAccountName, User ID or user principal name (UPN) as values for Identity. It has to do this to an extend because some values might or might not be available to identify a mailbox. Get-ADUser on the other hand has a much more strict approach only supporting distinguished name, GUID (objectGUID), security identifier (objectSid), SAM account name (sAMAccountName). Hence using the display name to find an AD account isn't supported. Your colleague used a filter to just use it anyway which is one solution $userinfo = Get-ADUser -filter { DisplayName -like $user } -Server A1.Domain ;.
If you really want to go with the display name you'll need to either look for it like that or use the DistinguishedName property of the mailbox to get the owner. So you'd do something like:
$mailbox = Get-Mailbox test
$adObject = Get-AdUser -Identity $mailbox.DistinguishedName
Obviously you should check whenever the property actually exists on the mailbox object as it might be disconnected. Also rather than using $user again and again you might want to use actual object (e.g. the mailbox or AD Object) to make sure you only need to verify your search results once.
You should also be able to just use one Set-AdUser call instead of that very weird call you're currently doing. You find the user, iterate the descriptions for the user (an object only has one) and add to it. Doing something like Set-AdUser $adObject -Description "New Description | $($adObject.Description)" would be much shorter and clearer. Spreading it some more might even improve it more.
I have been tasked with creating a bunch of security groups for Active Directory on a 2016 Windows Server. At the moment I have this code
$CSVLocation = Read-Host -Prompt "Please enter the path of CSV file"
$Groups = Import-CSV $CSVLocation
foreach ($Group in $Groups) {
$Groupname = Get-ADGroup -Identity $Group.Group
if ($Groupname -eq $null) {
New-ADGroup -Name $Group.Group -Path $group.GroupLocation -GroupScope $Group.GroupType
}
else {
echo "Group existes"
}
}
This is code is trying to create a group if that group doesn't exist and if it does then skip the entry in the CSV. As of this moment, all it does it pump out Get-ADGroup errors about how it can't find the group and then skips the creation of it.
The CSV format is like such:
Group,GroupType,GroupLocation
Group01,Universal,"OU=Test,DC=Example,DC=Local"
Group02,Universal,"OU=Test,DC=Example,DC=Local"
Group03,Universal,"OU=Test,DC=Example,DC=Local"
Error Message:
Get-ADGroup : Cannot find an object with identity: 'AU-CTX-RDP' under: 'DC=Example,DC=local'.
At C:\Users\Administrator\Desktop\Scripts\Import Groups.ps1:10 char:14
+ $Groupname = Get-ADGroup -Identity $Group.Group
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (AU-CTX-RDP:ADGroup) [Get-ADGroup], ADIdentityNotFoundException
+ FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException,Microsoft.ActiveDirectory.Management.Commands.GetADGroup
If you query for a not existing group you get a terminatig error. So the script execution would stop. To avoid this you can use -ErrorAction SilentlyContinue. This way it should work actually
$CSVLocation = Read-Host -Prompt "Please enter the path of CSV file"
$Groups = Import-CSV $CSVLocation
foreach ($Group in $Groups) {
if (-not (Get-ADGroup -Filter "Name -eq '$($group.Group)'" -ErrorAction SilentlyContinue)) {
New-ADGroup -Name $Group.Group -Path $group.GroupLocation -GroupScope $Group.GroupType
}
else {
"Group '$($Group.Group)' already exists"
}
}
Run this script to create bulk users in Powershell, Task will be completed within 30 seconds
New-ADGroup "-Name -GroupScope -GroupSecurity -GroupName" -Path “OU=OUWhereIStoreMyGroups" -Description
I am new to powershell Below scripts i have which remove all groups from the user member of tab except "Domain users" this works fine many time without any issues
Removing Groups from User
$list = Import-Csv c:\user\DN.csv
foreach ($entry in $list)
$UserDN = $entry.DistinguishedName
Get-ADGroup -LDAPFilter "(member=$UserDN)" | foreach-object {
if ($_.name -ne "Domain Users") {remove-adgroupmember -identity $_.name -member $UserDN -Confirm:$False}
But the problem is when if this script is not able to remove any group from user member of tab it throws an error below but it doesn't shows from which user id it was unable to remove the membership as the user distinguished name is imported from a CSV file.
Remove-ADGroupMember : The specified account name is not a member of the group
At C:\User\removegroups.ps1:35 char:115
+ Get-ADGroup -LDAPFilter "(member=$UserDN)" | foreach-object {if ($_.name -ne "Domain Users") {remove-adgroupmember <<
<< -identity $_.name -member $UserDN -Confirm:$False}
+ CategoryInfo : NotSpecified: (xyz:ADGroup) [Remove-ADGroupMember], ADException
+ FullyQualifiedErrorId : The specified account name is not a member of the group,Microsoft.ActiveDirectory.Management.Commands.RemoveADGroupMember
$list = Import-Csv c:\user\DN.csv
foreach ($entry in $list)
$UserDN = $entry.DistinguishedName
Get-ADGroup -LDAPFilter "(member=$UserDN)" | foreach-object {
if ($_.name -ne "Domain Users") {
try {
remove-adgroupmember -identity $_.name -member $UserDN -Confirm:$False} }
catch [ADexcption] {
write-output "Error Deleting User:" $_.name
}
}
Import-Csv DN.csv | foreach {
$user = Get-ADUser $_.username
$UserDN = $user.DistinguishedName
Get-ADGroup -LDAPFilter "(member=$UserDN)" | foreach-object {
if ($_.name -ne "Domain Users") {
try {
remove-adgroupmember -identity $_.name -member $UserDN -Confirm:$False
}
catch [ADexcption] {
write-output "Error Deleting User:" $_.name
}
}
}}