1
votes

I know the best practice is to use property values such as Name, Distinguishedname etc. However, I am working with two systems and the only field in Active Directory which is the same in both systems is extensionAttribute1. Below is the code. The error is with the foreach loop and not accepting the variable for -Identity.

Function ArchiveLeavers
{
Write-Host "Archiving leavers. Details below..."

$csvLeavers = Import-Csv -Path $fileLeavers      

    foreach ($user in $csvLeavers)
    {

    $csvID = $user.ExtensionAttribute1

    if (Get-ADUser -filter {extensionAttribute1 -eq $csvID} -SearchBase $LeaverOU)
    {
        Write-Host ($user.GivenName + ' ' + $user.LastName) " is already in leavers"
    }

    else
    {
        ForEach-Object  
        {
        $identity = Get-ADUser -filter {extensionAttribute1 -eq $csvID} | select distinguishedName | Format-Table -HideTableHeaders

        write-host ($user.GivenName + ' ' + $user.LastName) " needs moving"
        Move-ADObject -Identity $identity -TargetPath $LeaverOU;
        Set-ADUser    -Add @{extensionAttribute7=$user.ExtensionAttribute7}
        Write-Host ($user.GivenName + ' ' + $user.LastName) " has been moved"
        }

    }
  }
}

This is the Error:

Move-ADObject : Cannot convert 'System.Object[]' to the type 
    'Microsoft.ActiveDirectory.Management.ADObject' required by parameter 'Identity'. Specified 
    method is not supported.
    At line:21 char:57
    +Move-ADObject -Identity $identity -TargetPath $F ...
    +~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Move-ADObject], ParameterBindingException
    + FullyQualifiedErrorId : CannotConvertArgument,Microsoft.ActiveDirectory.Management.Commands.MoveADObject
1
Don't use Format-list/-table with variable assignments. They are only for formatting an output.Martin

1 Answers

2
votes

You are using Format-Table which convert your $Identity variable to object which is not known by Move-ADObject which get only input kind of SAM,Guid,SID etc.

Remove the Format-Table from the pipe, Change this:

$identity = Get-ADUser -filter {extensionAttribute1 -eq $csvID} | select distinguishedName | Format-Table -HideTableHeaders

To this:

$identity = Get-ADUser -filter {extensionAttribute1 -eq $csvID}