Powershell modifies user profiles

Source: Internet
Author: User
Tags symlink

Recently the company intends to uniformly modify some of the properties of the ad user, including the samaccountname,upn,office365 UPN, so that these properties and e-mail addresses are consistent. These changes are not difficult in themselves, can be implemented through PowerShell batch, the problem is that after the modification there are many additional issues, such as Outlook OST file, through the ad LDAP login tools, some software to save the path and other needs to deal with.


The first issue after modifying the ad logins is that the user profile on the computer needs to be modified synchronously. The company doesn't use SCCM, so it's up to itself. The beans have done some testing, basically do the following:

  1. Log on to the computer as a different administrator;

  2. Confirm that the user ABC has exited the login status and can be operated by Task Manager or Quser.

  3. Modify the C:\users\abc file name to the new user name C:\USERS\ABC1

  4. Modify the registry, which has a bunch of keys named according to the SID, need to find the corresponding, and then modify the corresponding ProfileImagePath

    HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList

    650) this.width=650; "src=" https://s1.51cto.com/wyfs02/M00/97/5E/wKioL1kuDQOhCuiZAACjCSYm6_s522.jpg "title=" 3.JPG "alt=" Wkiol1kudqohcuizaacjcsym6_s522.jpg "/>

  5. Create a new Symbolink connection from C:\users\abc <==> C:\USERS\ABC1. Windows has its own Mklink command that can be used, such as mklink/d C:\Users \abc C:\USERS\ABC1. PS5 can be created later with New-item, but earlier versions have no native PS commands, can only call cmd indirectly, or write a method of their own



The above actions can be implemented by PS script.

#创建SymLink的方法, this online discovery has a ready-made, I have directly downloaded function new-symlink {    <#     . synopsis        creates a symbolic link.     #>    param  (        [ Parameter (position=0, mandatory= $true)]        [string] $ Link,        [parameter (position=1, mandatory= $true)]         [string]  $Target     )      invoke-mklink -link  $Link  -Target  $Target  -symlink}function new-hardlink {     <#    . synopsis        creates a hard link.     #>    param  (     &Nbsp;  [parameter (position=0, mandatory= $true)]         [string]  $Link,         [parameter (position=1, mandatory=$ true)]        [string]  $Target     )      Invoke-MKLINK -Link  $Link  -Target  $Target  -HardLink}function  new-junction {    <#    . synopsis        creates a directory junction.     #>    param  (        [ Parameter (position=0, mandatory= $true)]        [string] $ Link,        [parameter (position=1, mandatory= $true)]         [string]  $Target     )     Invoke-MKLINK -Link  $Link  -Target  $Target  - junction}function invoke-mklink {    <#    . Synopsis        creates a symbolic link, hard  link, or directory junction.    #>    [ Cmdletbinding (defaultparametersetname =  "Symlink")]    param  (         [parameter (position=0, mandatory= $true)]         [string]  $Link,         [parameter ( position=1, mandatory= $true)]        [string]  $Target,         [parameter (parametersetname =  "Symlink")]         [switch]  $Symlink =  $true,         [parameter (ParameterSetName =   "Hardlink")]        [switch]  $HardLink,         [parameter (parametersetname =  "Junction")]         [switch]  $Junction     )     # ensure  target exists.    if  (-not (test-path  $Target))  {         throw  "target does not exist. ' ntarget:  $Target"     }    # Ensure link does not exist.     if  (test-path  $Link)  {        throw   "A file or directory already exists at the link path. ' NLink :  $Link "    }     $isDirectory  =  (get-item  $Target). psiscontainer     $mklinkArg  =  ""     if  ($Symlink  - and  $isDirectory)  {         $mkLinkArg  =  "/d"      }    if  ($Junction)  {         # Ensure we are linking a directory.  (Junctions don ' t  work for files.)         if  (-not ($isDirectory))  {             throw  "the target is a file.  Junctions cannot be created for files. ' ntarget:  $Target '          }         $mklinkArg  =  "/j"      }    if  ($HardLink)  {        # Ensure  we are linking a file.  (Hard links don ' t work for  Directories.)         if  ($isDirectory)  {             throw  "The target is a directory. hard  links cannot be created for directories. ' ntarget:  $Target '          }         $mkLinkArg  =  "/ H "    }    # capture the mklink output so  we can return it properly.    # Includes a  redirect of stderr to stdout so we can capture it as  Well.     $output  = cmd /c mklink  $mkLinkArg   ' $Link '   ' $Target ' " 2>&1     if  ($lastExitCode  -ne 0)  {         throw  "mklink failed. exit code:  $lastExitCode ' N$output"      }    else {        write-output   $output     }}    #定义一个Flag跳出循环 $flag = $truewhile ($flag) {      $oldName =read-host  "Please input the old user name"      write-host  ' Searching user profile. '  -ForegroundColor Cyan          #测试该用户是否已经登录, Here's a little trick. Convert the Quser string result to an object, specifically explaining the reference blog     http://beanxyz.blog.51cto.com/5570417/1906162     if  (test-path  "C:\Users\ $oldName") {&NBSP;&NBSP;&NBSP;&NBSP;&Nbsp;   write-host  "User profile c:\users\ $oldName  found."  -ForegroundColor Cyan         #Check  if the  user is currently logged in         $quser  =   (quser)  -replace  ' \s{2,17} ',  ', '  | ConvertFrom-Csv          $sessionId  =  $quser  | where-object { $_. username -eq  $newName  } | select -ExpandProperty id                   #如果已经登录, then forcibly exit this user          foreach ($id  in  $sessionId) {             if ($id  -ne  $null) {                 write-host  "detected user  $newName  still login"  -ForegroundColor red                 Write-Host  "Force  logoff the user " -ForegroundColor red                 logoff  $id              }                  }                  $newName =read-host  "Please input the new name"           $oldpath = "C:\Users\ $oldName"         $ Newpath= "C:\Users\ $newName"                    #重命名文件夹         rename-item  $oldpath   $newpath  -confirm - erroraction stop        write-host  "Searching Registry  Information  " -ForegroundColor Cyan                   #查询对应的注册表Key          get-childitem  "Hklm:\software\microsoft\windows nt\currentversion\profilelist"  | foreach{              #Get  the username from  SID             $sid =$_. Name.split (' \ ') [-1];                           #根据SID来匹配用户, if the user matches successfully, then modify the corresponding profilelist             try{             $objSID  =  New-Object System.Security.Principal.SecurityIdentifier  ($SID)               $objUser  =  $objSID. Translate ( [ System.Security.Principal.NTAccount])                $username = $objUser .value            }             catch{}              #change  registry keys             if (($username  -eq  "omnicom\ $oldName")  -or  ($username  - eq  "Omnicom\ $newName")) {                 write-host  "found  registry information of user profile  $newName " -ForegroundColor Cyan                  $keys = get-itemproperty  "Hklm:\software\microsoft\windows nt\currentversion\profilelist\ $sid"                    $keys. Profileimagepath= $newpath                  write-host  "registry key profile list is changed to $ NewPath " -ForegroundColor Cyan                                                      #调用上面的方法, creating Symbolink                 #Create  new  symbolink                # new-item -path  $oldpath  -ItemType Junction -Value  $newpath                  new-symlink -link $ oldpath -target  $newpath                                    break;            }             else{                 write-host  "$username  name not match ... skip " -foregroundcolor yellow                          }                  }         $flag = $false               }    else {         write-host  "profile is not found.  Please try again "&NBSP;-FOREGROUNDCOLOR&NBSP;RED&NBSP;&NBSP;&NBSP;&NBSP;}}


Execution effect, I directly throw this file to a remote computer under the C disk test, and then log in as a local administrator, execute this script, success!



650) this.width=650; "title=" 1.JPG "style=" Float:none; "src=" https://s5.51cto.com/wyfs02/M00/97/5E/ Wkiol1kude6dqavtaab2pbtll9c610.jpg "alt=" Wkiol1kude6dqavtaab2pbtll9c610.jpg "/>

650) this.width=650; "title=" 2.JPG "style=" Float:none; "src=" https://s4.51cto.com/wyfs02/M00/97/5D/ Wkiom1kude2d7jq7aagcqe23nj4312.jpg "alt=" Wkiom1kude2d7jq7aagcqe23nj4312.jpg "/>

This article is from the "Mapo Tofu" blog, please be sure to keep this source http://beanxyz.blog.51cto.com/5570417/1930788

Powershell modifies user profiles

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.