How to Replace Description Text for All Users in an Organizational Unit using Powershell

半腔热情 提交于 2019-12-13 19:47:26

问题


I have added about 1700+ users to Active Directory using a CSV file. I accidentially tried to use \n to seperate some attributes between them. But it did not escape new line. Instead typed it as is.

$Users = Import-Csv -Path "C:\UsersList.csv"            

foreach ($User in $Users)            
{
    $Name = $User.Name
    $AccountPassword = $User.AccountPassword
    $City = $User.City
    $Company = $User.Company
    $GivenName = $User.GivenName
    $SamAccountName = $User.SamAccountName      
    $Surname = $User.Surname
    $UserPrincipalName = $User.UPN
    $Displayname = $User.Name   
    $Description = "Desc1: " + $User.Desc1 + "\nDesc2: " + $User.Desc2 + "\nDesc3: " + $User.Desc3 + "\nDesc4: " + $User.Desc4
    $Path = $User.Path


    New-ADUser -Name "$Name" -DisplayName "$Displayname" -SamAccountName "$SamAccountName" -UserPrincipalName "$UserPrincipalName" -GivenName "$GivenName" -Surname "$Surname" -Description "$Description" -AccountPassword (ConvertTo-SecureString $AccountPassword -AsPlainText -Force) -Enabled $true -Path "$Path" -ChangePasswordAtLogon $true
}

Now I want to change those "\n" in Descriptions for all users.

I can get users using

Get-ADUser -Filter {description -like "\n"}

I need a command that using .Replace("\n"," - "). I do not know how to use it to reach my goal.


回答1:


You could do a Foreach-Object loop to find all the Descriptions with your filter and pipe that to Set-Aduser.

         $Description = "-Desc1: " + $User.Desc1 + "-Desc2: " + $User.Desc2 + "-Desc3: " + $User.Desc3 + "-Desc4: " + $User.Desc4

        foreach ($User in (Get-ADUser -Filter {description -like "*\n*"}) )
        {
            $User.SamAccountName | Set-ADUser -Description $Description
        }

To update the users from the CSV

            foreach ($User in $users )
            {
                $User.SamAccountName | Set-ADUser -Description $user.Description
            }



回答2:


Use Set-ADUser:

Get-ADUser -Filter {description -like "*\n*"} -Properties Description |
  ForEach-Object {
    $newDescription = $_.Description.Replace('\n', ' - ')
    Set-ADUser -Identity $_ -Description $newDescription
  }

Note that with the -like operator you need to add wildcards before and after the \n, otherwise you'd only get users where the description consists of just \n and nothing else. You also need to tell Get-ADUser to include the property Description as it isn't among the properties returned by default.



来源:https://stackoverflow.com/questions/36179855/how-to-replace-description-text-for-all-users-in-an-organizational-unit-using-po

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!