首页 > 解决方案 > 通过导出 .csv 文件,通过 Powershell 将禁用的用户移动到 AD 中的 OU

问题描述

以下是我的 .csv 文件中的所有参数。

上次登录日期、名字、姓氏、显示名称、用户登录名、帐户状态、用户主体名称、职位、部门、描述、办公室、电话号码、电子邮件、手机

我在 .csv 文件中有一个禁用用户列表。作为整理 AD 的一部分,我想将它们移动到我为暂停用户创建的新 OU。

我找到了以下使用sAMAccountNames移动禁用帐户的脚本,但我的参数中没有sAMAccountNames。我可以通过将 sAMAccountNames 替换为上述任何参数来使用以下脚本吗?

我可以通过将 sAMAccountNames 替换为用户登录名、用户主体名称或列表中的任何参数来使用以下脚本吗?我不想使用不是唯一的参数。

# Specify target OU.

$TargetOU = "ou=NewUsers,ou=West,dc=MyDomain,dc=com,dc=au"

# Read user sAMAccountNames from csv file (field labeled "Name").

Import-Csv -Path Users.csv | ForEach-Object {

# Retrieve DN of User.

$UserDN = (Get-ADUser -Identity $_.Name).distinguishedName

# Move user to target OU.

Move-ADObject -Identity $UserDN -TargetPath $TargetOU

}

# Read user LoginName (E-mail) from csv file (Label your fields Name and OU).
Import-Csv -Path "C:\---------------------------.csv " | ForEach-Object {
    # Retrieve DN of User, set target OU from list
    $UserDN = (Get-ADUser -Identity $_.E-mail).distinguishedName
    $TargetOU = $_.MoveTOOU
    # Move user to target OU.
    Move-ADObject -Identity $UserDN -TargetPath $TargetOU
}

这是发生的错误:

Get-ADUser : Cannot validate argument on parameter 'Identity'. The argument is null or an element of the 
argument collection contains a null value.
At line:7 char:37
+     $UserDN = (Get-ADUser -Identity $_.E-mail).distinguishedName
+                                     ~~~~
    + CategoryInfo          : InvalidData: (:) [Get-ADUser], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.ActiveDirectory.Management.Commands.GetADUser

使用电子邮件作为参数时出现错误。

标签: powershell

解决方案


在您的情况下,查看 CSV 文件中的字段,我会使用User principal nameorE-mail字段,因为它们在域中是唯一的。

由于您没有在 CSV 中指定目标 OU,因此将其设置在循环上方的变量中:

$TargetOU = 'OU=NewUsers,OU=West,DC=MyDomain,DC=com,DC=au'  # the DN of the OU to move the users to

Import-Csv -Path 'C:\Users\VedhaiyK\Desktop\HPA CleanUP\Upto2020OnlydisabledHPA.csv' | ForEach-Object {
    # Retrieve the UserPrincipalName from the CSV
    $userUPN = $_.'User principal name'
    # try and get an ADUser object using the UPN
    $User = Get-ADUser -Filter "UserPrincipalName -eq '$userUPN'" -ErrorAction SilentlyContinue
    if ($User) {
        # If found, move the user to the target OU.
        Move-ADObject -Identity $User.DistinguishedName -TargetPath $TargetOU
    }
    else {
        Write-Warning "User '$userUPN' does not exist"
    } 
}

推荐阅读