Share via


How to use Windows Authentication with the PSCredential class

Since posting the Remote Powershell sample I have had many people ask me how to make a connection to a remote endpoint using Windows Authentication instead of suppling a username and password as my sample demonstrates. I have changed the sample so that it looks for the presence of a username and password and if none is found it just creates a null PSCredential.  The null PSCredential causes Powershell to use Windows Authentication.  I have updated RemoteExchangePS.cs in my Remote Powershell sample.  The method GetExchangeServers has been changed to:

             if (userName.Length > 0 && password.Length > 0)

            {

                System.Security.SecureString securePassword = new System.Security.SecureString();

                foreach (char c in password.ToCharArray())

                {

                    securePassword.AppendChar(c);

                }

                creds = new PSCredential(userName, securePassword);

            }

            else

            {

                // Use Windows Authentication
creds = (PSCredential)null;

            }

If the client doesn't specify a username and password the code will now just use the security context in which it runs.  As long as the process running this code has permissions to execute this cmdlet the code should succeed.