【问题标题】:How to run PowerShell from C# as administrator?如何以管理员身份从 C# 运行 PowerShell?
【发布时间】:2020-03-08 18:48:24
【问题描述】:

我想通过 C# 执行一些 PowerShell 脚本,但它需要管理员权限。这是我的代码(我知道了here):

using (new Impersonator("user", "domain", "password"))
{
    // create Powershell runspace
    Runspace runspace = RunspaceFactory.CreateRunspace();

    // open it
    runspace.Open();

    // create a pipeline and feed it the script text
    Pipeline pipeline = runspace.CreatePipeline();
    pipeline.Commands.AddScript(scriptText);

    // add parameters if any
    foreach (var parameter in parameters)
    {
        pipeline.Commands[0].Parameters.Add(parameter.Key, parameter.Value);
    }

    // add an extra command to transform the script
    // output objects into nicely formatted strings

    // remove this line to get the actual objects
    // that the script returns. For example, the script

    // "Get-Process" returns a collection
    // of System.Diagnostics.Process instances.
    pipeline.Commands.Add("Out-String");

    // execute the script
    Collection<PSObject> results = pipeline.Invoke();

    // close the runspace
    runspace.Close();

    // convert the script result into a single string
    StringBuilder stringBuilder = new StringBuilder();
    foreach (PSObject obj in results)
    {
        stringBuilder.AppendLine(obj.ToString());
    }

    return stringBuilder.ToString();
}

无论如何,这在我的机器上不起作用。例如,如果脚本文本是“Set-ExecutionPolicy Unrestricted”,那么我会得到“Access to the registry key 'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell' is denied.

就我而言,它无法通过Get-VM 命令获取虚拟机列表。 (我发现Get-VM 只有在管理员权限下运行才会返回结果。)

我做错了吗?这个问题有其他解决方案吗?

【问题讨论】:

  • 不能以管理员身份运行吗?
  • 我通过 C# 运行它,所以我试图弄清楚如何做到这一点。 :)
  • 如果您以管理员身份运行应用程序(或者如果直接从 Visual Studio 运行,则以管理员身份运行 Visual Studio),它启动的进程应自动以管理员身份运行。
  • 此代码将成为网站的一部分,不允许以管理员身份运行网站。
  • 通过网站访问注册表和/或执行 power-shell 是个好主意吗?

标签: c# powershell


【解决方案1】:

这将以管理员身份启动 PowerShell:

var newProcessInfo = new System.Diagnostics.ProcessStartInfo();
newProcessInfo.FileName = @"C:\Windows\SysWOW64\WindowsPowerShell\v1.0\powershell.exe";
newProcessInfo.Verb = "runas";
System.Diagnostics.Process.Start(newProcessInfo);

如果你需要传入一个脚本来运行,那么使用:

newProcessInfo.Arguments = @"C:\path\to\script.ps1";

【讨论】:

    猜你喜欢
    • 2016-01-25
    • 2010-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-14
    • 2016-12-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多