开发者

Change some windows username programmatically (Rename windows user)

How to change windows user name programmatically (using some API or 开发者_运维问答command line tool) Or how to rename a windows user?


I have written some small method to rename a windows user using System.DirectoryServices.DirectoryEntry class.

public bool RenameUser(string oldLoginName, string newLoginName)
{
    bool renamed = false;
    try
    {
        using (DirectoryEntry AD = new
                   DirectoryEntry("WinNT://" + Environment.MachineName + ",computer"))
        {
            try
            {
                using (DirectoryEntry NewUser = AD.Children.Find(oldLoginName, "user"))
                {
                    if (NewUser != null)
                    {
                        NewUser.Rename(newLoginName);
                        renamed = true;
                    }
                }
            }
            catch (Exception ex)
            {
                //TODO: Log
            }
        }
    }
    catch (Exception ex)
    {
         //TODO: Log
    }
    return renamed;
}


You can change the username of a user account with the NetUserSetInfo function.

If you only want to change the username set the level argument to 0 and pass a USER_INFO_0 structure. You can use a different level if you want to change several things at once.

This is a simple bit of code I've used successfully to change usernames:

#include <Windows.h>
#include <LM.h>

#include <stdio.h>

#pragma comment(lib, "netapi32.lib")

int main(int argc, char ** argv)
{
    USER_INFO_0 ui0;
    NET_API_STATUS result;
    LPWSTR command = GetCommandLineW();
    wchar_t newname[21];

    while (*command != L'*') command++;

    command++;

    ui0.usri0_name = newname;
    wcscpy_s(newname, _countof(newname), L"decommiss-");
    wcscat_s(newname, _countof(newname), command);

    result = NetUserSetInfo(NULL, command, 0, (LPBYTE)&ui0, NULL);

    printf("%u\n", result);

    return result;
}    


You can not change obviously the name of the user on Windows system, as it kind of key for a lot of internal resources, but you can change DisplayName of it, which, by the way, will not affect on internal File structure, so kind of cosmetic change. Which most probably will create confusion for you, or for other users on the same machine along years of use, so I would suggest do not do that. But if you want, here is powershell script example, that should work for you :

  $CurrentUserName = "Your_Domain_Name/Current_User_Name" 
    Get-QADUser -SearchRoot $CurrentUserName  `
    | Set-QADUser -DisplayName "New_User_Name" `
    | FT FirstName, LastName, DisplayName, company

For more detailed description look on this good example:

Change user DisplayName from powershell

Note that here they use extraplugin for PowerShell.

EDIT

another link on subject to clarify what I mean :

Change user name on Windows7 Professional

Hope this helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜