试图从变量

时间:2016-03-10 14:14:03

标签: powershell active-directory

我知道最佳做法是使用NameDistinguishedname等属性值。但是,我正在使用两个系统,并且Active Directory中唯一的字段在两个系统中都是相同的是extensionAttribute1。下面是代码。错误在于foreach循环,并且不接受-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"
        }

    }
  }
}

这是错误:

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 个答案:

答案 0 :(得分:2)

您正在使用格式表将$Identity变量转换为Move-ADObject所不知道的对象,该对象仅获取SAM,Guid,SID等输入类型。

从管道中删除Format-Table,更改:

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

对此:

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