Share via

Revert from command to C#

Scott Huang 3,511 Reputation points
2022-03-19T09:57:10.997+00:00

Hi,
How to revert from AddScript to C# code (on the line below) that we cannot create user further as the user is existing?

ps.AddScript("if($userName -eq $null) {$userName = \"may.chen\"}")

Windows for business | Windows Server | User experience | PowerShell
Developer technologies | C#
Developer technologies | C#

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.

0 comments No comments

Answer accepted by question author

Castorix31 91,876 Reputation points
2022-03-20T08:08:04.24+00:00

If you want to check if a local user exists before adding it, there are plenty of methods

You can do for example :

 bool Exists = IsUserExists("testUser");

with :

        private bool IsUserExists(string sUserName)
        {           
            DirectoryEntry deComputer = new DirectoryEntry("WinNT://" + Environment.MachineName + ", computer");
            DirectoryEntries entries = deComputer.Children;
            foreach (DirectoryEntry de in entries)
            {
                if (de.Name.Equals(sUserName, StringComparison.CurrentCultureIgnoreCase))
                    return true;
            }
            return false;
        }

Was this answer helpful?

0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Rich Matheisen 48,116 Reputation points
    2022-03-19T19:42:58.957+00:00

    Are you asking how to an AD user and then modify its properties using c#?

    how-can-i-get-a-list-of-users-from-active-directory
    how-to-update-active-directory-attributes-using-c

    Was this answer helpful?


Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.