简体   繁体   中英

How to run Power shell as Administrator

My codes runs perfectly when i run it as Admin. but it gave an error when i run it as guest:

An internal error occurred.

Is there any way i can configure to run power shell as Admin programmatic?

string shellUri = "http://schemas.microsoft.com/powershell/Microsoft.PowerShell";
string password = "****";
System.Security.SecureString securePW = new System.Security.SecureString();
foreach (char c in password)
        securePW.AppendChar(c);
securePW.MakeReadOnly();
string domainAndUsername = @"192.168.1.113\***";
string remoteMachineName = "****";
PSCredential remoteCredential = new PSCredential(domainAndUsername, securePW);
WSManConnectionInfo connectionInfo = new WSManConnectionInfo(false, remoteMachineName, 5985, "/wsman", shellUri, remoteCredential);

using (Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo)) //_Error Here_//

I found some solutions but they are OLD, they don't work anymore :S

If you use Process you can run as admin using below:

var processStartInfo = new ProcessStartInfo("powershell")
            {
                UseShellExecute = true,
                CreateNoWindow = true,
                Verb = "runas",
                //UserName = username,
                //Password = MakeSecureString(password)
            };
            var exec = Process.Start(processStartInfo);
            exec?.WaitForExit(0);

If you don't want prompt, then you will have to change UAC. And you can pass arguments to process object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM