如何以管理员身份运行Power shell

时间:2015-10-26 07:37:16

标签: c# powershell

当我以管理员身份运行时,我的代码运行完美。但是当我以客人身份运行它时出错:

  

发生内部错误。

我有什么方法可以配置为以管理员编程方式运行power shell吗?

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_//

我找到了一些解决方案,但他们是旧的,他们不再工作了:S

1 个答案:

答案 0 :(得分:1)

如果您使用Process,则可以使用以下命令以管理员身份运行:

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

如果您不想提示,则必须更改UAC。你可以将参数传递给进程对象。