Skip to content

Instantly share code, notes, and snippets.

@Romern
Last active March 20, 2025 14:46
Show Gist options
  • Save Romern/cb6864971ac13fac30ca3bb69d1edd60 to your computer and use it in GitHub Desktop.
Save Romern/cb6864971ac13fac30ca3bb69d1edd60 to your computer and use it in GitHub Desktop.
Add user to group
#include <windows.h>
#include <lm.h>
#include <stdio.h>
#pragma comment(lib, "Netapi32.lib")
void CreateUser(LPCWSTR userName, LPCWSTR password) {
USER_INFO_1 userInfo;
NET_API_STATUS status;
ZeroMemory(&userInfo, sizeof(userInfo));
userInfo.usri1_name = (LPWSTR)userName;
userInfo.usri1_password = (LPWSTR)password;
userInfo.usri1_priv = USER_PRIV_USER; // Normal user
userInfo.usri1_home_dir = NULL;
userInfo.usri1_comment = L"Created by C program";
userInfo.usri1_flags = UF_SCRIPT | UF_DONT_EXPIRE_PASSWD; // User must not change password
status = NetUserAdd(NULL, 1, (LPBYTE)&userInfo, NULL);
if (status == NERR_Success) {
wprintf(L"User '%s' created successfully.\n", userName);
} else if (status == NERR_UserExists) {
wprintf(L"User '%s' already exists.\n", userName);
} else {
wprintf(L"Failed to create user. Error: %d\n", status);
}
}
void AddUserToLocalGroup(LPCWSTR userName, LPCWSTR groupName) {
LOCALGROUP_MEMBERS_INFO_3 memberInfo;
NET_API_STATUS status;
memberInfo.lgrmi3_domainandname = (LPWSTR)userName;
status = NetLocalGroupAddMembers(NULL, groupName, 3, (LPBYTE)&memberInfo, 1);
if (status == NERR_Success) {
wprintf(L"User '%s' added to group '%s' successfully.\n", userName, groupName);
} else if (status == NERR_GroupNotFound) {
wprintf(L"Group '%s' does not exist.\n", groupName);
} else {
wprintf(L"Failed to add user to group. Error: %d\n", status
#include <windows.h>
#include <lm.h>
#include <stdio.h>
#pragma comment(lib, "Netapi32.lib")
void AddUserToLocalGroup(LPCWSTR userName, LPCWSTR groupName) {
LOCALGROUP_MEMBERS_INFO_3 memberInfo;
NET_API_STATUS status;
memberInfo.lgrmi3_domainandname = (LPWSTR)userName;
status = NetLocalGroupAddMembers(NULL, groupName, 3, (LPBYTE)&memberInfo, 1);
if (status == NERR_Success) {
wprintf(L"User '%s' added to group '%s' successfully.\n", userName, groupName);
} else {
wprintf(L"Failed to add user to group. Error: %d\n", status);
}
}
int wmain(int argc, wchar_t *argv[]) {
if (argc != 3) {
wprintf(L"Usage: %s <username> <groupname>\n", argv[0]);
return 1;
}
AddUserToLocalGroup(argv[1], argv[2]);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment