执行的PowerShell从C#管理员 [英] Execute PowerShell as an administrator from C#

查看:590
本文介绍了执行的PowerShell从C#管理员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下面的C#code

I have the following C# code

using (RunspaceInvoke invoker = new RunspaceInvoke())
{
  invoker.Invoke("Set-ExecutionPolicy Unrestricted");
  // ...
}

这使我异常

访问注册表项
  HKEY_LOCAL_MACHINE \\ SOFTWARE \\微软\\的PowerShell \\ 1 \\ ShellIds \\ Microsoft.P​​owerShell
  被拒绝。

Access to the registry key 'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell' is denied.

根据这个,解决的办法是开始的PowerShell为管理员。

According to this, the solution is to start PowerShell as an administrator.

通常情况下,这可以通过完成右击PowerShell和选择以管理员身份运行。有没有办法做到这一点编程?

Ordinarily, this can be accomplished by right-clicking PowerShell and selecting "Run as Administrator". Is there a way to do this programmatically?

推荐答案

您需要模拟作为管理员做到这一点(你当然会需要管理员凭据)

You need to impersonate as an administrator to do it (you will of course need administrator credentials)

检查文章,认为还带有code准备使用(我用它和它的伟大工程)

Check that article, that also comes with code ready to use (I've used it and it works great)

基本上,你需要这样做:

Basically, you need to do this:

using ( new Impersonator( "myUsername", "myDomainname", "myPassword" ) )
{
    using (RunspaceInvoke invoker = new RunspaceInvoke())
    {
        invoker.Invoke("Set-ExecutionPolicy Unrestricted");
    }
}

这篇关于执行的PowerShell从C#管理员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆