簡體   English   中英

從 PSCmdlet 類 (C#) 在主機 Powershell 中調用原始命令

[英]Invoke Raw Command in Host Powershell from PSCmdlet class (C#)

我正在玩 PSCmdlet 類。

有沒有辦法可以在執行我的命令的主機 powershell 中調用命令?

例如:

我想做一個函數來設置一些別名。

public void myAliases() {
// Invoke Set-Alias in host ?
}

我嘗試實例化Powershell.Create()AddCommand()但對我不起作用。

提前致謝!

您可以使用 c# 編寫類庫並擴展 PSCmdlet 以創建可直接在 powershell 中使用的方法。

要做到這一點,您將需要一個方法,並聲明它將如何調用

    [Cmdlet("Lookup", "Aliases")]
    public class LookupAliases: PSCmdlet 
    {

        [Parameter(Mandatory = true,
            ValueFromPipeline = false,
            ValueFromPipelineByPropertyName = false,
            ParameterSetName = "1",
            HelpMessage = "Indicates the help message")]
        public string FirstArgument{ get; set; }

        protected override void ProcessRecord()
        {
            // write your process here.
            base.ProcessRecord();
        }
    }

在powershell中,您需要導入您在上面創建的這個dll(編譯解決方案)並在powershell中運行

Lookup-Aliases -FirstArugment "value"

如果您想在 c# 中運行 powershell 命令,

    Runspace runSpace = RunspaceFactory.CreateRunspace();
    runSpace.Open();

    Pipeline pipeline = runSpace.CreatePipeline();

    string script = "your powershell script here";
    pipeline.Commands.AddScript(script);

    Collection<PSObject> output = pipeline.Invoke();

暫無
暫無

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

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