I'm trying to run some PowerShell to move users to different OU and disable the account.
Here is my code
$ADUsers = Import-Xlsx 'C:\User Creation\ADUsersRemoval.xlsx' | Foreach {
$test = Get-ADUser -LdapFilter "samaccountname -eq '$("$Firstname.$Lastname")" |
Move-ADObject -TargetPath "OU=Users,OU=Graveyard,DC=domain,DC=dc" -PassThru |
Disable-ADAccount
}
}
The code runs without errors but doesn't do anything to the user account. What am I doing wrong?
Update
I realized I missed adding the values for $Firstname
and $Lastname
.
Here is a code I tested with.
$ADUsers = Import-Xlsx 'C:\User Creation\ADUsersRemoval.xlsx'
foreach ($User in $ADUsers) {
$Firstname = $User.Firstname
$Lastname = $User.Lastname
Get-ADUser -Filter "samaccountname -eq '$("$Firstname.$Lastname")'" -Properties 'mail'
}
}
Now works absolutely fine, gives me the details below. clearly reading from my xlsx file ps. Doing it with '$("$Firstname.$Lastname")'"
works fine. Any other way then it won't read the xlsx file.
PSComputerName : server RunspaceId : **************************************** DistinguishedName : CN=user65 test65,CN=Users,DC=domain,DC=com Enabled : True GivenName : user65 mail : [email protected] Name : user65 test65 ObjectClass : user ObjectGUID : afc3fc3b-c43a-4e1b-ad83-804ee605eb00 SamAccountName : user65.test65 SID :************************************* Surname : test65 UserPrincipalName : [email protected]
but when trying to do the task of moving user and disabling. it doesn't action
$ADUsers = Import-Xlsx 'C:\User Creation\ADUsersRemoval.xlsx'
foreach ($User in $ADUsers) {
$Firstname = $User.Firstname
$Lastname = $User.Lastname
Get-ADUser -Filter "samaccountname -eq '$("$Firstname.$Lastname")'" |
Move-ADObject -TargetPath "OU=Users,OU=Graveyard,DC=domain,DC=com" -PassThru |
Disable-ADAccount
}
-filter
instead of-ldapfilter
since you have the syntax for-filter
already. You also have an opening single quote without a closing single quote. I would tryGet-ADUser -Filter "samaccountname -eq '$("$Firstname.$Lastname")'"
– AdminOfThings'$("$Firstname.$Lastname")'
should probably be'${Firstname}.${Lastname}'
. Why do people feel the need to put everything into subexpressions? – Ansgar Wiechers'$("$Firstname.$Lastname")"
coming from? that looks like it should be$_.FirstName
or whatever is in your CSV import. [2] will anything at all be in $Test? from what i can tell,
Disable-ADAccount` has no output unless you add-PassThru
to its parameters. – Lee_Dailey$Firstname
and$Lastname
are undefined, and your code uses the parameter-LdapFilter
with a value for the parameter-Filter
. Please create a minimal reproducible example, test-run that code to make sure it still exposes the problem you're trying to debug, then edit your question and copy/paste that code along with sample input and all errors thrown by it. – Ansgar WiechersSamAccountName
has the form ofFirstName.LastName
? – Theo