簡體   English   中英

如何以管理員身份從 C# 運行 PowerShell?

[英]How to run PowerShell from C# as administrator?

我想通過 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虛擬機列表。 (我發現Get-VM只有在以管理員權限運行時才返回結果。)

我做錯了什么嗎? 這個問題還有其他解決方案嗎?

這將以管理員身份啟動 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";

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM