Code is not working

Working on a script to disable and move users to another OU. It works on a single user, trying to get things to work from a input file. here is the code
import-module activedirectory
$InFile=read-host “Enter user list file name?”
$UserList=Import-Csv -Path $InFile
ForEach ($Username in $UserList) {

$ADUser = Get-ADUser -Identity $Username -Properties MemberOf
If ($ADUser -eq $Null)
{
#User not found
Write-Host “User not found” -ForegroundColor Red
} else {
#User Found
If ($ADUser.Enabled -eq $True)
{
Write-Host “User is not disabled” -ForegroundColor Yellow
} else {
#User is disabled
[array]$Groups = $AdUser.MemberOf
Foreach ($Group in $Groups)
{
Write-Host “Working on: $Group”
Remove-ADGroupMember -Identity “$Group” -Members $($ADUser.SamAccountName) -Confirm:$false
}
}
}
}
#Move the LDW employee AD account to disabled account OU
Get-ADUser $username | Move-ADObject -TargetPath (path removed)
It fails here:
$ADUser = Get-ADUser -Identity $Username -Properties MemberOf

Please go back and format your code with the ‘</>’ button and also what is the error message?

Also what is in the CSV file? Import-Csv will create an array of PSCustomObjects and will have the column names as the Properties, so you likely need to access the propery name everywhere you have $Username.

For example if the column in the CSV is username then $Username should be $Username.username

3 Likes

I concur with @neemobeer here.

$UserList is going to be a Collection of 1 or more ‘rows’ of your CSV, essentially a powershell representation of your CSV file. When you loop through it, you need to specify the property you’re referencing or, you need to handle that in your import like so:

$UserList = Import-CSV -Path $InFile | Select-Object -ExpandProperty Username

This code snippet assumes the property (header) in your CSV is Username. I’m assuming here that your CSV is just one column. You could simply copy this and put it in the corresponding line, and update whatever your header is as well.

1 Like