如何以管理员身份从 C# 运行 PowerShell

本文关键字:运行 PowerShell 身份 管理员 | 更新日期: 2023-09-27 18:36:27

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

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# 运行 PowerShell

这将以管理员身份启动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";